Skip to content

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

feat: C4 architecture diagrams (L1-L3) — closes #203 (#204)

Raghav Chamadiya7171739cdebb
diff --git a/README.md b/README.md
index 3bce29a94..f7188e10d 100644
--- a/README.md
+++ b/README.md
@@ -255,6 +255,7 @@ This is what happens when an AI agent has real codebase intelligence.
| **Chat** | Ask anything about your codebase in natural language |
| **Docs** | AI-generated wiki with syntax highlighting, Mermaid diagrams, and a graph intelligence sidebar showing PageRank/betweenness percentiles, community membership, and degree |
| **Graph** | Interactive dependency graph — handles 2,000+ nodes. Community color mode with real labels, community detail panel on click, path finder |
+| **C4 Architecture** | C4-model view of the codebase (Context → Containers → Components) with drill-down, URL-synced state, and a per-node detail panel that surfaces module health, top contributors, and the generated wiki page inline |
| **Search** | Full-text and semantic search with global command palette (Ctrl+K) |
| **Symbols** | Searchable index of every function, class, and method, server-ranked by importance (PageRank × visibility × complexity × kind × entry-point). Filter facets for public-only, language, kind, in-hotspot-files, and in-entry-point-files. Click any symbol for graph metrics, callers/callees, class heritage, and a git panel with governing decisions |
| **Coverage** | Doc freshness per file with one-click regeneration |
diff --git a/packages/core/alembic/versions/0018_external_systems.py b/packages/core/alembic/versions/0018_external_systems.py
new file mode 100644
index 000000000..91920a940
--- /dev/null
+++ b/packages/core/alembic/versions/0018_external_systems.py
@@ -0,0 +1,80 @@
+"""Add external_systems table and graph_nodes.external_system_id FK.
+
+Powers C4 L1 (System Context) by persisting third-party dependencies parsed
+from repo manifests (package.json, pyproject.toml, Cargo.toml, go.mod,
+.csproj). Each GraphNode that represents an `external:*` import can be linked
+to a row here so renderers know the dep's name, version, category, ecosystem.
+
+Revision ID: 0018
+Revises: 0017
+Create Date: 2026-05-17
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "0018"
+down_revision = "0017"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "external_systems",
+ sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
+ sa.Column(
+ "repository_id",
+ sa.String(32),
+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("name", sa.String(255), nullable=False),
+ sa.Column("display_name", sa.String(255), nullable=False, server_default=""),
+ sa.Column("ecosystem", sa.String(32), nullable=False),
+ sa.Column("category", sa.String(32), nullable=False, server_default="library"),
+ sa.Column("version", sa.String(64), nullable=True),
+ sa.Column("declared_in", sa.Text(), nullable=False),
+ sa.Column("is_dev_dep", sa.Boolean(), nullable=False, server_default=sa.false()),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ nullable=False,
+ server_default=sa.func.now(),
+ ),
+ sa.UniqueConstraint(
+ "repository_id", "name", "declared_in", name="uq_external_system"
+ ),
+ )
+ op.create_index(
+ "ix_external_systems_repository_id",
+ "external_systems",
+ ["repository_id"],
+ )
+
+ with op.batch_alter_table("graph_nodes") as batch_op:
+ batch_op.add_column(
+ sa.Column("external_system_id", sa.Integer(), nullable=True)
+ )
+ batch_op.create_foreign_key(
+ "fk_graph_nodes_external_system",
+ "external_systems",
+ ["external_system_id"],
+ ["id"],
+ ondelete="SET NULL",
+ )
+ op.create_index(
+ "ix_graph_nodes_external_system_id",
+ "graph_nodes",
+ ["external_system_id"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("ix_graph_nodes_external_system_id", table_name="graph_nodes")
+ with op.batch_alter_table("graph_nodes") as batch_op:
+ batch_op.drop_constraint("fk_graph_nodes_external_system", type_="foreignkey")
+ batch_op.drop_column("external_system_id")
+
+ op.drop_index("ix_external_systems_repository_id", table_name="external_systems")
+ op.drop_table("external_systems")
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/base.py b/packages/core/src/repowise/core/ingestion/external_systems/base.py
new file mode 100644
index 000000000..899fdb30a
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/external_systems/base.py
@@ -0,0 +1,47 @@
+"""Common types for manifest parsers.
+
+Each ecosystem-specific parser (npm, pypi, cargo, go, nuget) implements the
+``ManifestParser`` protocol below and returns a list of
+``ExternalSystemRecord`` instances. The orchestrator stitches them together
+and persists them via ``crud.upsert_external_systems``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Protocol
+
+
+@dataclass(frozen=True)
+class ExternalSystemRecord:
+ """Plain-data dependency record. Mirrors the ExternalSystem ORM row but
+ is kept dialect-free so parsers don't depend on the persistence layer.
+ """
+
+ name: str
+ ecosystem: str
+ declared_in: str # repo-relative path to the manifest file
+ version: str | None = None
+ display_name: str = ""
+ category: str = "library" # populated by classifier
+ is_dev_dep: bool = False
+ extras: dict[str, str] = field(default_factory=dict)
+
+
+class ManifestParser(Protocol):
+ """Stateless parser for one manifest format.
+
+ Implementations should be pure functions of (manifest_path, repo_root)
+ and never raise on malformed input — return an empty list instead and
+ let the caller log a warning. Ingestion must not crash because one
+ repo ships a broken pyproject.toml.
+ """
+
+ #: Filenames this parser handles, e.g., ("package.json",).
+ filenames: tuple[str, ...]
+
+ ecosystem: str
+
+ def parse(self, manifest_path: Path, repo_root: Path) -> list[ExternalSystemRecord]:
+ ...
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/cargo.py b/packages/core/src/repowise/core/ingestion/external_systems/cargo.py
new file mode 100644
index 000000000..bb7948ad2
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/external_systems/cargo.py
@@ -0,0 +1,80 @@
+"""Parse Rust ``Cargo.toml`` manifests.
+
+Captures ``[dependencies]``, ``[dev-dependencies]``, ``[build-dependencies]``.
+Workspace members and path/git dependencies are skipped — those are
+first-party containers, not external systems.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+try:
+ import tomllib # type: ignore[import-not-found]
+except ModuleNotFoundError: # pragma: no cover — Python <3.11
+ import tomli as tomllib # type: ignore[no-redef]
+
+from .base import ExternalSystemRecord
+from .classifier import classify, display_name_for
+
+filenames: tuple[str, ...] = ("Cargo.toml",)
+ecosystem: str = "cargo"
+
+_SECTIONS: tuple[tuple[str, bool], ...] = (
+ ("dependencies", False),
+ ("dev-dependencies", True),
+ ("build-dependencies", False),
+)
+
+
+def parse(manifest_path: Path, repo_root: Path) -> list[ExternalSystemRecord]:
+ try:
+ data = tomllib.loads(manifest_path.read_text(encoding="utf-8"))
+ except (OSError, tomllib.TOMLDecodeError):
+ return []
+ if not isinstance(data, dict):
+ return []
+
+ declared_in = manifest_path.relative_to(repo_root).as_posix()
+ records: list[ExternalSystemRecord] = []
+ seen: set[str] = set()
+
+ for section, is_dev in _SECTIONS:
+ block = data.get(section)
+ if not isinstance(block, dict):
+ continue
+ for raw_name, spec in block.items():
+ if _is_path_or_git(spec):
+ continue
+ name = str(raw_name).strip()
+ if not name or name in seen:
+ continue
+ seen.add(name)
+ version = _spec_version(spec)
+ records.append(
+ ExternalSystemRecord(
+ name=name,
+ ecosystem=ecosystem,
+ declared_in=declared_in,
+ version=version,
+ display_name=display_name_for(name),
+ category=classify(name),
+ is_dev_dep=is_dev,
+ )
+ )
+ return records
+
+
+def _spec_version(spec: object) -> str | None:
+ if isinstance(spec, str):
+ s = spec.strip()
+ return s or None
+ if isinstance(spec, dict):
+ v = spec.get("version")
+ if isinstance(v, str):
+ return v.strip() or None
+ return None
+
+
+def _is_path_or_git(spec: object) -> bool:
+ return isinstance(spec, dict) and ("path" in spec or "git" in spec)
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/classifier.py b/packages/core/src/repowise/core/ingestion/external_systems/classifier.py
new file mode 100644
index 000000000..61e8c361a
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/external_systems/classifier.py
@@ -0,0 +1,81 @@
+"""Heuristic classifier mapping dependency names to C4 categories.
+
+Categories:
+ framework — opinionated runtime/HTTP/UI framework (fastapi, next, react,
+ django, rails, spring, ...).
+ service — represents an external SaaS / cloud / infra dependency the
+ app talks to over the network (stripe, aws-sdk, openai,
+ supabase, sentry, ...).
+ tool — build/test/lint/typecheck tooling that wouldn't usually
+ appear in an architecture diagram for the running system
+ (eslint, vitest, ruff, pytest, mypy, ...).
+ library — default catch-all.
+
+The dictionary is intentionally small and conservative — we'd rather
+mis-classify as ``library`` than as ``service`` (a wrong "service" causes
+fake boundaries in the C4 diagram). Extend it as we see real repos.
+"""
+
+from __future__ import annotations
+
+import re
+
+_FRAMEWORK_NAMES: frozenset[str] = frozenset({
+ "fastapi", "django", "flask", "starlette", "tornado", "bottle",
+ "next", "nextjs", "react", "vue", "svelte", "nuxt", "remix",
+ "astro", "solid-js", "preact", "ember",
+ "express", "koa", "hapi", "nestjs", "@nestjs/core",
+ "rails", "sinatra", "spring", "spring-boot",
+ "rocket", "actix-web", "axum", "warp",
+ "gin", "echo", "fiber", "chi",
+ "aspnetcore",
+})
+
+_SERVICE_NAMES: frozenset[str] = frozenset({
+ "stripe", "twilio", "sendgrid", "mailgun", "postmark",
+ "openai", "anthropic", "cohere", "together",
+ "supabase", "@supabase/supabase-js", "firebase", "firebase-admin",
+ "redis", "ioredis", "pymongo", "psycopg2", "psycopg", "asyncpg",
+ "sqlalchemy", "prisma", "@prisma/client", "drizzle-orm", "typeorm",
+ "sentry-sdk", "@sentry/node", "@sentry/nextjs", "posthog-js", "posthog-node",
+ "modal",
+})
+
+_SERVICE_PATTERNS: tuple[re.Pattern[str], ...] = (
+ re.compile(r"^@aws-sdk/"),
+ re.compile(r"^boto3?$"),
+ re.compile(r"^@azure/"),
+ re.compile(r"^@google-cloud/"),
+ re.compile(r"^google-cloud-"),
+)
+
+_TOOL_NAMES: frozenset[str] = frozenset({
+ "eslint", "prettier", "typescript", "ts-node", "tsx",
+ "vitest", "jest", "mocha", "chai", "cypress", "playwright",
+ "webpack", "vite", "rollup", "esbuild", "parcel", "turbopack",
+ "ruff", "black", "mypy", "pyright", "pytest", "pytest-asyncio",
+ "tox", "nox", "coverage", "pylint", "flake8", "isort",
+ "alembic",
+})
+
+
+def classify(name: str) -> str:
+ """Return one of: ``framework``, ``service``, ``tool``, ``library``."""
+ key = name.lower()
+ if key in _FRAMEWORK_NAMES:
+ return "framework"
+ if key in _SERVICE_NAMES:
+ return "service"
+ for pat in _SERVICE_PATTERNS:
+ if pat.match(key):
+ return "service"
+ if key in _TOOL_NAMES:
+ return "tool"
+ return "library"
+
+
+def display_name_for(name: str) -> str:
+ """Best-effort prettifier: strip scope, replace separators, title-case."""
+ base = name.split("/")[-1] if name.startswith("@") else name
+ base = base.replace("-", " ").replace("_", " ")
+ return base.title()
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/go.py b/packages/core/src/repowise/core/ingestion/external_systems/go.py
new file mode 100644
index 000000000..ad49690d3
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/external_systems/go.py
@@ -0,0 +1,98 @@
+"""Parse Go ``go.mod`` manifests.
+
+Single-line ``require module v1.2.3`` and ``require ( ... )`` blocks are
+both handled. ``// indirect`` comments mark transitive deps — we flag those
+as dev-deps so the C4 view can de-clutter L1 by hiding them by default.
+``replace`` directives are honored: any replacement that points at a local
+path drops the module from the result set (it's a container, not external).
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from .base import ExternalSystemRecord
+from .classifier import classify, display_name_for
+
+filenames: tuple[str, ...] = ("go.mod",)
+ecosystem: str = "go"
+
+_REQ_LINE = re.compile(r"^\s*([^\s]+)\s+([^\s]+)(?:\s*//\s*(indirect))?\s*$")
+_REPLACE_LINE = re.compile(r"^\s*([^\s]+)(?:\s+[^\s]+)?\s*=>\s*(\S+)")
+
+
+def parse(manifest_path: Path, repo_root: Path) -> list[ExternalSystemRecord]:
+ try:
+ text = manifest_path.read_text(encoding="utf-8")
+ except OSError:
+ return []
+
+ declared_in = manifest_path.relative_to(repo_root).as_posix()
+ replaced_by_local: set[str] = set()
+ requires: list[tuple[str, str, bool]] = [] # (name, version, is_indirect)
+
+ in_require = False
+ in_replace = False
+ for raw in text.splitlines():
+ line = raw.strip()
+ if not line or line.startswith("//"):
+ continue
+ # Single-line forms
+ if line.startswith("require ") and "(" not in line:
+ entry = line[len("require ") :].strip()
+ m = _REQ_LINE.match(entry)
+ if m:
+ requires.append((m.group(1), m.group(2), bool(m.group(3))))
+ continue
+ if line.startswith("replace ") and "(" not in line:
+ entry = line[len("replace ") :].strip()
+ _handle_replace(entry, replaced_by_local)
+ continue
+ # Block forms
+ if line.startswith("require ("):
+ in_require = True
+ continue
+ if line.startswith("replace ("):
+ in_replace = True
+ continue
+ if line == ")":
+ in_require = in_replace = False
+ continue
+ if in_require:
+ m = _REQ_LINE.match(line)
+ if m:
+ requires.append((m.group(1), m.group(2), bool(m.group(3))))
+ elif in_replace:
+ _handle_replace(line, replaced_by_local)
+
+ records: list[ExternalSystemRecord] = []
+ seen: set[str] = set()
+ for name, version, indirect in requires:
+ if name in replaced_by_local or name in seen:
+ continue
+ seen.add(name)
+ records.append(
+ ExternalSystemRecord(
+ name=name,
+ ecosystem=ecosystem,
+ declared_in=declared_in,
+ version=version,
+ display_name=display_name_for(name.split("/")[-1]),
+ category=classify(name.split("/")[-1]),
+ is_dev_dep=indirect,
+ )
+ )
+ return records
+
+
+def _handle_replace(entry: str, replaced_by_local: set[str]) -> None:
+ m = _REPLACE_LINE.match(entry)
+ if not m:
+ return
+ name, target = m.group(1), m.group(2)
+ # A local path replacement looks like ``./foo`` or ``../bar`` or an
+ # absolute filesystem path. Remote module replacements look like
+ # ``github.com/x/y``.
+ if target.startswith(".") or target.startswith("/") or (len(target) > 1 and target[1] == ":"):
+ replaced_by_local.add(name)
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/npm.py b/packages/core/src/repowise/core/ingestion/external_systems/npm.py
new file mode 100644
index 000000000..f017fb681
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/external_systems/npm.py
@@ -0,0 +1,102 @@
+"""Parse npm/yarn/pnpm ``package.json`` manifests.
+
+Captures ``dependencies``, ``devDependencies``, ``peerDependencies``, and
+``optionalDependencies``. Workspace metadata is ignored — workspace packages
+are containers, not external systems.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from .base import ExternalSystemRecord
+from .classifier import classify, display_name_for
+
+filenames: tuple[str, ...] = ("package.json",)
+ecosystem: str = "npm"
+
+_DEP_FIELDS: tuple[tuple[str, bool], ...] = (
+ ("dependencies", False),
+ ("devDependencies", True),
+ ("peerDependencies", False),
+ ("optionalDependencies", False),
+)
+
+
+def parse(manifest_path: Path, repo_root: Path) -> list[ExternalSystemRecord]:
+ try:
+ data = json.loads(manifest_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return []
+ if not isinstance(data, dict):
+ return []
+
+ declared_in = manifest_path.relative_to(repo_root).as_posix()
+ workspace_names = _collect_workspace_names(data, manifest_path, repo_root)
+
+ records: list[ExternalSystemRecord] = []
+ seen: set[str] = set()
+ for field_name, is_dev in _DEP_FIELDS:
+ block = data.get(field_name)
+ if not isinstance(block, dict):
+ continue
+ for raw_name, raw_version in block.items():
+ name = str(raw_name).strip()
+ if not name or name in seen or name in workspace_names:
+ continue
+ seen.add(name)
+ version = _normalize_version(raw_version)
+ records.append(
+ ExternalSystemRecord(
+ name=name,
+ ecosystem=ecosystem,
+ declared_in=declared_in,
+ version=version,
+ display_name=display_name_for(name),
+ category=classify(name),
+ is_dev_dep=is_dev,
+ )
+ )
+ return records
+
+
+def _normalize_version(value: object) -> str | None:
+ if not isinstance(value, str):
+ return None
+ v = value.strip()
+ return v or None
+
+
+def _collect_workspace_names(
+ data: dict[str, object], manifest_path: Path, repo_root: Path
+) -> set[str]:
+ """Read ``workspaces`` globs and return the names of each sibling package.
+
+ We rely on this set to skip workspace deps that appear as version ``*``
+ or ``workspace:*`` in a parent package.json — those are first-party
+ containers, not external systems.
+ """
+ workspaces = data.get("workspaces")
+ patterns: list[str] = []
+ if isinstance(workspaces, list):
+ patterns = [str(p) for p in workspaces if isinstance(p, str)]
+ elif isinstance(workspaces, dict):
+ packages = workspaces.get("packages")
+ if isinstance(packages, list):
+ patterns = [str(p) for p in packages if isinstance(p, str)]
+ if not patterns:
+ return set()
+
+ root = manifest_path.parent
+ names: set[str] = set()
+ for pat in patterns:
+ for match in root.glob(pat + "/package.json"):
+ try:
+ inner = json.loads(match.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ inner_name = inner.get("name") if isinstance(inner, dict) else None
+ if isinstance(inner_name, str) and inner_name:
+ names.add(inner_name)
+ return names
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/nuget.py b/packages/core/src/repowise/core/ingestion/external_systems/nuget.py
new file mode 100644
index 000000000..9d1c3812d
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/external_systems/nuget.py
@@ -0,0 +1,62 @@
+"""Parse .NET ``.csproj`` files for ``<PackageReference>`` entries.
+
+We deliberately use ``xml.etree.ElementTree`` rather than a real XML parser
+to keep the dependency footprint small; .csproj files are simple enough.
+``<ProjectReference>`` entries point at sibling projects and are skipped —
+those are containers, not external systems.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from xml.etree import ElementTree as ET
+
+from .base import ExternalSystemRecord
+from .classifier import classify, display_name_for
+
+# .csproj filenames are repo-specific; the discovery layer matches "*.csproj".
+filenames: tuple[str, ...] = ()
+ecosystem: str = "nuget"
+
+
+def parse(manifest_path: Path, repo_root: Path) -> list[ExternalSystemRecord]:
+ try:
+ tree = ET.parse(manifest_path)
+ except (OSError, ET.ParseError):
+ return []
+ root = tree.getroot()
+
+ declared_in = manifest_path.relative_to(repo_root).as_posix()
+ records: list[ExternalSystemRecord] = []
+ seen: set[str] = set()
+
+ for elem in root.iter():
+ # Strip XML namespace if present
+ tag = elem.tag.split("}", 1)[-1] if "}" in elem.tag else elem.tag
+ if tag != "PackageReference":
+ continue
+ name = (elem.get("Include") or elem.get("Update") or "").strip()
+ if not name or name in seen:
+ continue
+ seen.add(name)
+ version = elem.get("Version") or _child_text(elem, "Version")
+ records.append(
+ ExternalSystemRecord(
+ name=name,
+ ecosystem=ecosystem,
+ declared_in=declared_in,
+ version=version.strip() if version else None,
+ display_name=display_name_for(name.split(".")[-1]),
+ category=classify(name),
+ is_dev_dep=False,
+ )
+ )
+ return records
+
+
+def _child_text(elem: ET.Element, child_tag: str) -> str | None:
+ for child in elem:
+ tag = child.tag.split("}", 1)[-1] if "}" in child.tag else child.tag
+ if tag == child_tag and child.text:
+ return child.text
+ return None
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/pypi.py b/packages/core/src/repowise/core/ingestion/external_systems/pypi.py
new file mode 100644
index 000000000..aeec6bbf7
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/external_systems/pypi.py
@@ -0,0 +1,171 @@
+"""Parse Python manifests: ``pyproject.toml`` (PEP 621) and ``requirements*.txt``.
+
+``pyproject.toml`` covers PEP 621 (``[project] dependencies``,
+``[project.optional-dependencies]``) and the older Poetry layout
+(``[tool.poetry.dependencies]``, ``[tool.poetry.group.*.dependencies]``).
+``requirements*.txt`` is parsed line-by-line.
+
+Sibling repowise/internal packages (anything declared as a workspace member
+or path dependency) are skipped — they are containers, not external systems.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+try:
+ import tomllib # type: ignore[import-not-found]
+except ModuleNotFoundError: # pragma: no cover — Python <3.11
+ import tomli as tomllib # type: ignore[no-redef]
+
+from .base import ExternalSystemRecord
+from .classifier import classify, display_name_for
+
+filenames: tuple[str, ...] = ("pyproject.toml",)
+ecosystem: str = "pypi"
+
+_REQ_LINE = re.compile(
+ r"""^
+ \s*
+ (?P<name>[A-Za-z0-9_][A-Za-z0-9_.\-]*)
+ (?:\[[^\]]*\])?
+ \s*
+ (?P<spec>[^;#\s]*)
+ """,
+ re.VERBOSE,
+)
+
+
+def parse(manifest_path: Path, repo_root: Path) -> list[ExternalSystemRecord]:
+ name = manifest_path.name
+ if name == "pyproject.toml":
+ return _parse_pyproject(manifest_path, repo_root)
+ if name.startswith("requirements") and name.endswith(".txt"):
+ return _parse_requirements(manifest_path, repo_root, is_dev="dev" in name.lower())
+ return []
+
+
+def _parse_pyproject(manifest_path: Path, repo_root: Path) -> list[ExternalSystemRecord]:
+ try:
+ data = tomllib.loads(manifest_path.read_text(encoding="utf-8"))
+ except (OSError, tomllib.TOMLDecodeError):
+ return []
+ if not isinstance(data, dict):
+ return []
+
+ declared_in = manifest_path.relative_to(repo_root).as_posix()
+ records: list[ExternalSystemRecord] = []
+ seen: set[str] = set()
+
+ project = data.get("project")
+ if isinstance(project, dict):
+ for entry in project.get("dependencies", []) or []:
+ _add_pep508(records, seen, entry, declared_in, is_dev=False)
+ opt = project.get("optional-dependencies")
+ if isinstance(opt, dict):
+ for group, entries in opt.items():
+ is_dev = group in {"dev", "test", "tests", "lint", "docs", "typing"}
+ for entry in entries or []:
+ _add_pep508(records, seen, entry, declared_in, is_dev=is_dev)
+
+ poetry = data.get("tool", {}).get("poetry") if isinstance(data.get("tool"), dict) else None
+ if isinstance(poetry, dict):
+ for raw_name, spec in (poetry.get("dependencies") or {}).items():
+ if raw_name == "python":
+ continue
+ if _is_path_dep(spec):
+ continue
+ _add_simple(records, seen, str(raw_name), _spec_version(spec), declared_in, is_dev=False)
+ groups = poetry.get("group")
+ if isinstance(groups, dict):
+ for group_name, group_data in groups.items():
+ is_dev = group_name in {"dev", "test", "tests", "lint", "docs"}
+ deps = group_data.get("dependencies") if isinstance(group_data, dict) else None
+ if not isinstance(deps, dict):
+ continue
+ for raw_name, spec in deps.items():
+ if _is_path_dep(spec):
+ continue
+ _add_simple(records, seen, str(raw_name), _spec_version(spec), declared_in, is_dev=is_dev)
+
+ return records
+
+
+def _parse_requirements(
+ manifest_path: Path, repo_root: Path, *, is_dev: bool
+) -> list[ExternalSystemRecord]:
+ try:
+ text = manifest_path.read_text(encoding="utf-8")
+ except OSError:
+ return []
+ declared_in = manifest_path.relative_to(repo_root).as_posix()
+ records: list[ExternalSystemRecord] = []
+ seen: set[str] = set()
+ for raw in text.splitlines():
+ line = raw.split("#", 1)[0].strip()
+ if not line or line.startswith("-"):
+ continue
+ _add_pep508(records, seen, line, declared_in, is_dev=is_dev)
+ return records
+
+
+def _add_pep508(
+ records: list[ExternalSystemRecord],
+ seen: set[str],
+ entry: str,
+ declared_in: str,
+ *,
+ is_dev: bool,
+) -> None:
+ if not isinstance(entry, str):
+ return
+ match = _REQ_LINE.match(entry)
+ if not match:
+ return
+ name = match.group("name").strip()
+ if not name:
+ return
+ version = match.group("spec").strip() or None
+ _add_simple(records, seen, name, version, declared_in, is_dev=is_dev)
+
+
+def _add_simple(
+ records: list[ExternalSystemRecord],
+ seen: set[str],
+ name: str,
+ version: str | None,
+ declared_in: str,
+ *,
+ is_dev: bool,
+) -> None:
+ key = name.lower()
+ if key in seen:
+ return
+ seen.add(key)
+ records.append(
+ ExternalSystemRecord(
+ name=name,
+ ecosystem=ecosystem,
+ declared_in=declared_in,
+ version=version,
+ display_name=display_name_for(name),
+ category=classify(name),
+ is_dev_dep=is_dev,
+ )
+ )
+
+
+def _spec_version(spec: object) -> str | None:
+ if isinstance(spec, str):
+ s = spec.strip()
+ return s or None
+ if isinstance(spec, dict):
+ v = spec.get("version")
+ if isinstance(v, str):
+ return v.strip() or None
+ return None
+
+
+def _is_path_dep(spec: object) -> bool:
+ return isinstance(spec, dict) and ("path" in spec or "git" in spec)
diff --git a/packages/core/src/repowise/core/persistence/__init__.py b/packages/core/src/repowise/core/persistence/__init__.py
index 95607d7b5..66b0052b9 100644
--- a/packages/core/src/repowise/core/persistence/__init__.py
+++ b/packages/core/src/repowise/core/persistence/__init__.py
@@ -21,6 +21,9 @@ from .crud import (
batch_upsert_graph_nodes,
batch_upsert_symbols,
bulk_upsert_decisions,
+ bulk_upsert_external_systems,
+ link_graph_nodes_to_external_systems,
+ list_external_systems,
count_chat_messages,
create_chat_message,
create_conversation,
@@ -91,6 +94,7 @@ from .models import (
Conversation,
DeadCodeFinding,
DecisionRecord,
+ ExternalSystem,
GenerationJob,
GitMetadata,
GraphEdge,
@@ -121,6 +125,7 @@ __all__ = [
"DecisionRecord",
# embedder
"Embedder",
+ "ExternalSystem",
# search
"FullTextSearch",
"GenerationJob",
@@ -146,6 +151,10 @@ __all__ = [
"batch_upsert_symbols",
# decision crud
"bulk_upsert_decisions",
+ # external systems crud (C4 L1)
+ "bulk_upsert_external_systems",
+ "link_graph_nodes_to_external_systems",
+ "list_external_systems",
# chat crud
"count_chat_messages",
# graph read-side queries
diff --git a/packages/core/src/repowise/core/persistence/crud.py b/packages/core/src/repowise/core/persistence/crud.py
index 22380ac40..e34b77c9c 100644
--- a/packages/core/src/repowise/core/persistence/crud.py
+++ b/packages/core/src/repowise/core/persistence/crud.py
@@ -26,6 +26,7 @@ from .models import (
Conversation,
DeadCodeFinding,
DecisionRecord,
+ ExternalSystem,
GenerationJob,
GitMetadata,
GraphEdge,
@@ -521,6 +522,107 @@ async def batch_upsert_graph_edges(
await session.flush()
+# ---------------------------------------------------------------------------
+# ExternalSystem CRUD
+# ---------------------------------------------------------------------------
+
+
+async def bulk_upsert_external_systems(
+ session: AsyncSession,
+ repository_id: str,
+ systems: list[dict],
+) -> dict[tuple[str, str], int]:
+ """Upsert external systems for a repository.
+
+ Each element of *systems* is a dict with keys matching ``ExternalSystem``
+ columns (excluding ``id``, ``repository_id``, ``created_at``).
+
+ Returns a mapping of ``(name, declared_in)`` → row ``id`` for both newly
+ inserted and existing rows, so callers can link ``graph_nodes`` to the
+ persisted external system without an extra round-trip.
+ """
+ id_map: dict[tuple[str, str], int] = {}
+ for sys_data in systems:
+ name = sys_data.get("name", "")
+ declared_in = sys_data.get("declared_in", "")
+ if not name:
+ continue
+ result = await session.execute(
+ select(ExternalSystem).where(
+ ExternalSystem.repository_id == repository_id,
+ ExternalSystem.name == name,
+ ExternalSystem.declared_in == declared_in,
+ )
+ )
+ existing = result.scalar_one_or_none()
+ if existing is not None:
+ for key, val in sys_data.items():
+ if key not in ("id", "repository_id", "created_at") and hasattr(existing, key):
+ setattr(existing, key, val)
+ id_map[(name, declared_in)] = existing.id
+ else:
+ row = ExternalSystem(
+ repository_id=repository_id,
+ **{k: v for k, v in sys_data.items() if k not in ("id", "repository_id")},
+ )
+ session.add(row)
+ await session.flush()
+ id_map[(name, declared_in)] = row.id
+ await session.flush()
+ return id_map
+
+
+async def link_graph_nodes_to_external_systems(
+ session: AsyncSession,
+ repository_id: str,
+ name_to_id: dict[str, int],
+) -> int:
+ """Resolve ``external:{name}`` graph nodes to their ExternalSystem row.
+
+ ``name_to_id`` should be a flat map of dep name → ExternalSystem id
+ (collapse multi-manifest entries by picking any id — the C4 renderer
+ only needs ``name``/``category`` which are the same across rows).
+
+ Returns the number of graph_nodes updated.
+ """
+ if not name_to_id:
+ return 0
+ prefix = "external:"
+ result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repository_id,
+ GraphNode.node_id.like(f"{prefix}%"),
+ )
+ )
+ updated = 0
+ for node in result.scalars():
+ suffix = node.node_id[len(prefix) :]
+ # Try the full suffix first, then the first segment (handles e.g.
+ # ``external:fastapi.responses`` → ``fastapi``).
+ sys_id = name_to_id.get(suffix)
+ if sys_id is None and "." in suffix:
+ sys_id = name_to_id.get(suffix.split(".", 1)[0])
+ if sys_id is None and "/" in suffix:
+ sys_id = name_to_id.get(suffix.split("/", 1)[0])
+ if sys_id is not None and node.external_system_id != sys_id:
+ node.external_system_id = sys_id
+ updated += 1
+ await session.flush()
+ return updated
+
+
+async def list_external_systems(
+ session: AsyncSession, repository_id: str
+) -> list[ExternalSystem]:
+ """List all external systems for a repository, ordered by name."""
+ result = await session.execute(
+ select(ExternalSystem)
+ .where(ExternalSystem.repository_id == repository_id)
+ .order_by(ExternalSystem.name)
+ )
+ return list(result.scalars())
+
+
# ---------------------------------------------------------------------------
# WikiSymbol CRUD (batch)
# ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 4ce670e8b..315199f51 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -176,6 +176,11 @@ class GraphNode(Base):
visibility: Mapped[str | None] = mapped_column(String(16), nullable=True)
signature: Mapped[str | None] = mapped_column(Text, nullable=True)
parent_symbol_id: Mapped[str | None] = mapped_column(Text, nullable=True)
+ # Set when this node represents an `external:*` import that we resolved to
+ # a known third-party dependency declared in a manifest. Powers C4 L1.
+ external_system_id: Mapped[int | None] = mapped_column(
+ Integer, ForeignKey("external_systems.id", ondelete="SET NULL"), nullable=True, index=True
+ )
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now_utc
)
@@ -183,6 +188,37 @@ class GraphNode(Base):
__table_args__ = (UniqueConstraint("repository_id", "node_id", name="uq_graph_node"),)
+class ExternalSystem(Base):
+ """A third-party dependency declared in a repo manifest (package.json,
+ pyproject.toml, Cargo.toml, go.mod, .csproj).
+
+ Populated during ingestion by repowise.core.ingestion.external_systems.
+ Consumed by the C4 builder service to render L1 (System Context) and the
+ external boundary of L2/L3.
+ """
+
+ __tablename__ = "external_systems"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
+ repository_id: Mapped[str] = mapped_column(
+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False, index=True
+ )
+ name: Mapped[str] = mapped_column(String(255), nullable=False)
+ display_name: Mapped[str] = mapped_column(String(255), nullable=False, default="")
+ ecosystem: Mapped[str] = mapped_column(String(32), nullable=False)
+ category: Mapped[str] = mapped_column(String(32), nullable=False, default="library")
+ version: Mapped[str | None] = mapped_column(String(64), nullable=True)
+ declared_in: Mapped[str] = mapped_column(Text, nullable=False)
+ is_dev_dep: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=_now_utc
+ )
+
+ __table_args__ = (
+ UniqueConstraint("repository_id", "name", "declared_in", name="uq_external_system"),
+ )
+
+
class GraphEdge(Base):
__tablename__ = "graph_edges"
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.py
index b10e394e8..38084a6d3 100644
--- a/packages/core/src/repowise/core/pipeline/orchestrator.py
+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py
@@ -148,6 +148,12 @@ class PipelineResult:
# data module. Populated post-traversal during the graph build phase.
tech_stack: list[dict] = field(default_factory=list)
+ # External systems parsed from repo manifests (package.json,
+ # pyproject.toml, Cargo.toml, go.mod, .csproj). Powers the C4 L1
+ # System Context view. Plain dicts mirroring ExternalSystemRecord fields
+ # for the same reason as tech_stack.
+ external_systems: list[dict] = field(default_factory=list)
+
# ---------------------------------------------------------------------------
# Pipeline
@@ -274,6 +280,34 @@ async def run_pipeline(
if git_meta_map:
graph_builder.add_co_change_edges(git_meta_map)
+ # ---- External systems (C4 L1) ------------------------------------------
+ # Parse repo manifests for declared third-party dependencies. Failure here
+ # must not break the pipeline — log and continue with an empty list.
+ external_systems: list[dict] = []
+ try:
+ from repowise.core.ingestion.external_systems import extract_external_systems
+
+ records = await asyncio.to_thread(extract_external_systems, repo_path)
+ external_systems = [
+ {
+ "name": r.name,
+ "display_name": r.display_name,
+ "ecosystem": r.ecosystem,
+ "category": r.category,
+ "version": r.version,
+ "declared_in": r.declared_in,
+ "is_dev_dep": r.is_dev_dep,
+ }
+ for r in records
+ ]
+ if progress and external_systems:
+ progress.on_message(
+ "info",
+ f"→ External systems: {len(external_systems):,} declared deps across manifests",
+ )
+ except Exception as _ext_err: # noqa: BLE001
+ logger.warning("external_systems_extraction_failed", error=str(_ext_err))
+
# Emit rich insight summary for the ingestion phase
if progress:
_g = graph_builder.graph()
@@ -399,6 +433,7 @@ async def run_pipeline(
{"name": t.name, "version": t.version, "category": t.category}
for t in tech_items
],
+ external_systems=external_systems,
)
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 74bd01d1a..ff87bb8ca 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -125,6 +125,8 @@ async def persist_pipeline_result(
batch_upsert_graph_edges,
batch_upsert_graph_nodes,
batch_upsert_symbols,
+ bulk_upsert_external_systems,
+ link_graph_nodes_to_external_systems,
upsert_page_from_generated,
)
from repowise.core.persistence.crud import (
@@ -165,6 +167,18 @@ async def persist_pipeline_result(
if edges:
await batch_upsert_graph_edges(session, repo_id, edges)
+ # ---- External systems (C4 L1) -------------------------------------------
+ # Persist before symbols so the FK linkage step below sees the IDs.
+ external_systems = getattr(result, "external_systems", None) or []
+ if external_systems:
+ id_map = await bulk_upsert_external_systems(session, repo_id, external_systems)
+ # Collapse multi-manifest duplicates: any id for a given name is fine
+ # (renderer only needs name/category/ecosystem which are stable).
+ name_to_id: dict[str, int] = {}
+ for (name, _declared_in), sys_id in id_map.items():
+ name_to_id.setdefault(name, sys_id)
+ await link_graph_nodes_to_external_systems(session, repo_id, name_to_id)
+
# ---- Symbols -------------------------------------------------------------
# NOTE: This mutates sym.file_path on the caller's PipelineResult objects.
# The guard prevents double-set on retries, but callers should treat the
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index 1dee89527..466f4311d 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -29,6 +29,7 @@ from repowise.core.providers.embedding.base import MockEmbedder
from repowise.server import __version__
from repowise.server.routers import (
blast_radius,
+ c4,
chat,
claude_md,
costs,
@@ -333,6 +334,7 @@ def create_app() -> FastAPI:
app.include_router(jobs.router)
app.include_router(symbols.router)
app.include_router(graph.router)
+ app.include_router(c4.router)
app.include_router(webhooks.router)
app.include_router(git.router)
app.include_router(dead_code.router)
diff --git a/packages/server/src/repowise/server/routers/c4.py b/packages/server/src/repowise/server/routers/c4.py
new file mode 100644
index 000000000..dd6bbeca6
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/c4.py
@@ -0,0 +1,187 @@
+"""/api/graph/{repo_id}/c4 — C4 architecture diagram endpoints.
+
+Three levels:
+ L1 System Context — the system + people + external systems
+ L2 Containers — workspace packages + external deps + edges
+ L3 Components — sub-modules inside one container + edges
+
+The shapes match ``server.schemas.C4L*Response`` and are derived on demand
+from the persisted graph by :mod:`server.services.c4_builder`. No on-disk
+work happens here, so this works on hosted backends without a checkout.
+"""
+
+from __future__ import annotations
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from fastapi.responses import PlainTextResponse
+from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.schemas import (
+ C4ComponentResponse,
+ C4ContainerResponse,
+ C4ExternalSystemResponse,
+ C4L1Response,
+ C4L2Response,
+ C4L3Response,
+ C4PersonResponse,
+ C4RelationResponse,
+ C4SystemResponse,
+)
+from repowise.server.services import c4_builder
+from repowise.server.services.c4_builder.mermaid import (
+ to_mermaid_l1,
+ to_mermaid_l2,
+ to_mermaid_l3,
+)
+from repowise.server.services.c4_builder.models import (
+ Component,
+ Container,
+ ExternalSystemView,
+ Person,
+ Relation,
+ System,
+)
+
+router = APIRouter(
+ prefix="/api/graph",
+ tags=["c4"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+
[email protected]("/{repo_id}/c4/l1", response_model=C4L1Response)
+async def get_c4_l1(
+ repo_id: str,
+ session: AsyncSession = Depends(get_db_session),
+) -> C4L1Response:
+ view = await c4_builder.build_l1(session, repo_id)
+ return C4L1Response(
+ system=_system(view.system),
+ people=[_person(p) for p in view.people],
+ external_systems=[_external(e) for e in view.external_systems],
+ relations=[_relation(r) for r in view.relations],
+ )
+
+
[email protected]("/{repo_id}/c4/l2", response_model=C4L2Response)
+async def get_c4_l2(
+ repo_id: str,
+ session: AsyncSession = Depends(get_db_session),
+) -> C4L2Response:
+ 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],
+ relations=[_relation(r) for r in view.relations],
+ )
+
+
[email protected]("/{repo_id}/c4/l3", response_model=C4L3Response)
+async def get_c4_l3(
+ repo_id: str,
+ container_id: str = Query(..., description="Container id from L2 (e.g., pkg:packages/core)"),
+ session: AsyncSession = Depends(get_db_session),
+) -> C4L3Response:
+ view = await c4_builder.build_l3(session, repo_id, container_id)
+ if view is None:
+ raise HTTPException(status_code=404, detail=f"container not found: {container_id}")
+ return C4L3Response(
+ container=_container(view.container),
+ components=[_component(c) for c in view.components],
+ external_systems=[_external(e) for e in view.external_systems],
+ relations=[_relation(r) for r in view.relations],
+ )
+
+
+ "/{repo_id}/c4/mermaid",
+ response_class=PlainTextResponse,
+ responses={200: {"content": {"text/plain": {}}}},
+)
+async def get_c4_mermaid(
+ repo_id: str,
+ level: int = Query(2, ge=1, le=3, description="C4 level: 1, 2, or 3"),
+ container_id: str | None = Query(None, description="Required when level=3"),
+ session: AsyncSession = Depends(get_db_session),
+) -> PlainTextResponse:
+ """Mermaid C4 source for the requested level — paste into mermaid.live or
+ embed in markdown. Same data source as the JSON endpoints, so what you
+ see in the diagram view matches what you export.
+ """
+ if level == 1:
+ view_l1 = await c4_builder.build_l1(session, repo_id)
+ return PlainTextResponse(to_mermaid_l1(view_l1))
+
+ if level == 2:
+ view_l2 = await c4_builder.build_l2(session, repo_id)
+ repo = await c4_builder._load_repo(session, repo_id)
+ system_name = repo.name if repo is not None else repo_id
+ return PlainTextResponse(to_mermaid_l2(view_l2, system_name=system_name))
+
+ if not container_id:
+ raise HTTPException(status_code=400, detail="container_id is required for level=3")
+ view_l3 = await c4_builder.build_l3(session, repo_id, container_id)
+ if view_l3 is None:
+ raise HTTPException(status_code=404, detail=f"container not found: {container_id}")
+ repo = await c4_builder._load_repo(session, repo_id)
+ system_name = repo.name if repo is not None else repo_id
+ return PlainTextResponse(to_mermaid_l3(view_l3, system_name=system_name))
+
+
+# ---------------------------------------------------------------------------
+# Dataclass → Pydantic adapters (kept tiny on purpose)
+# ---------------------------------------------------------------------------
+
+
+def _system(s: System) -> C4SystemResponse:
+ return C4SystemResponse(id=s.id, name=s.name, description=s.description)
+
+
+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,
+ name=c.name,
+ path=c.path,
+ language=c.language,
+ file_count=c.file_count,
+ symbol_count=c.symbol_count,
+ hotspot_count=c.hotspot_count,
+ dead_count=c.dead_count,
+ )
+
+
+def _component(c: Component) -> C4ComponentResponse:
+ return C4ComponentResponse(
+ id=c.id,
+ name=c.name,
+ path=c.path,
+ container_id=c.container_id,
+ file_count=c.file_count,
+ symbol_count=c.symbol_count,
+ )
+
+
+def _relation(r: Relation) -> C4RelationResponse:
+ return C4RelationResponse(
+ source_id=r.source_id,
+ target_id=r.target_id,
+ label=r.label,
+ edge_count=r.edge_count,
+ edge_types=list(r.edge_types),
+ )
diff --git a/packages/server/src/repowise/server/schemas.py b/packages/server/src/repowise/server/schemas.py
index 5cd4a512e..ae480c83e 100644
--- a/packages/server/src/repowise/server/schemas.py
+++ b/packages/server/src/repowise/server/schemas.py
@@ -1321,3 +1321,77 @@ class ReviewerSuggestion(BaseModel):
class ReviewerSuggestionsResponse(BaseModel):
paths: list[str]
suggestions: list[ReviewerSuggestion]
+
+
+# ---------------------------------------------------------------------------
+# C4 diagrams (L1 System Context, L2 Containers, L3 Components)
+# ---------------------------------------------------------------------------
+
+
+class C4PersonResponse(BaseModel):
+ id: str
+ name: str
+ description: str = ""
+
+
+class C4SystemResponse(BaseModel):
+ id: str
+ name: str
+ description: str = ""
+
+
+class C4ExternalSystemResponse(BaseModel):
+ id: str
+ name: str
+ display_name: str
+ category: str # framework | service | tool | library
+ ecosystem: str
+ version: str | None = None
+
+
+class C4ContainerResponse(BaseModel):
+ id: str
+ name: str
+ path: str
+ language: str
+ file_count: int
+ symbol_count: int
+ hotspot_count: int = 0
+ dead_count: int = 0
+
+
+class C4ComponentResponse(BaseModel):
+ id: str
+ name: str
+ path: str
+ container_id: str
+ file_count: int
+ symbol_count: int
+
+
+class C4RelationResponse(BaseModel):
+ source_id: str
+ target_id: str
+ label: str = ""
+ edge_count: int = 1
+ edge_types: list[str] = Field(default_factory=list)
+
+
+class C4L1Response(BaseModel):
+ system: C4SystemResponse
+ people: list[C4PersonResponse]
+ external_systems: list[C4ExternalSystemResponse]
+ relations: list[C4RelationResponse]
+
+
+class C4L2Response(BaseModel):
+ containers: list[C4ContainerResponse]
+ external_systems: list[C4ExternalSystemResponse]
+ relations: list[C4RelationResponse]
+
+
+class C4L3Response(BaseModel):
+ container: C4ContainerResponse
+ components: list[C4ComponentResponse]
+ external_systems: list[C4ExternalSystemResponse]
+ relations: list[C4RelationResponse]
diff --git a/packages/server/src/repowise/server/services/c4_builder/__init__.py b/packages/server/src/repowise/server/services/c4_builder/__init__.py
new file mode 100644
index 000000000..5498f4bb4
--- /dev/null
+++ b/packages/server/src/repowise/server/services/c4_builder/__init__.py
@@ -0,0 +1,236 @@
+"""C4 diagram builder service.
+
+Public API
+----------
+``build_l1(session, repo)`` returns System Context (system + external systems).
+``build_l2(session, repo)`` returns Container view + cross-container edges
+ + edges to external systems.
+``build_l3(session, repo, container_id)`` returns Component view for one
+ container + its in/out edges to other containers and external systems.
+
+All three reuse the same persisted graph (``graph_nodes``, ``graph_edges``)
+and the ``external_systems`` table populated during ingestion. No on-disk
+re-scan is performed at request time.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+
+from repowise.core.persistence import ExternalSystem, Repository
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from .components import detect_components
+from .containers import container_id, detect_containers
+from .models import (
+ C4L1,
+ C4L2,
+ C4L3,
+ Component,
+ Container,
+ ExternalSystemView,
+ Person,
+ Relation,
+ System,
+)
+from .relations import aggregate_relations, external_node_to_system_id
+
+__all__ = [
+ "C4L1",
+ "C4L2",
+ "C4L3",
+ "Component",
+ "Container",
+ "ExternalSystemView",
+ "Person",
+ "Relation",
+ "System",
+ "build_l1",
+ "build_l2",
+ "build_l3",
+ "container_id",
+]
+
+
+async def _load_repo(session: AsyncSession, repo_id: str) -> Repository | None:
+ result = await session.execute(select(Repository).where(Repository.id == repo_id))
+ return result.scalar_one_or_none()
+
+
+async def _external_views(
+ session: AsyncSession, repo_id: str
+) -> tuple[list[ExternalSystemView], dict[str, str]]:
+ """Return the deduplicated list of ExternalSystemView (one per name) and
+ a map from each name → ``ext:<name>`` id.
+
+ Multi-manifest deps collapse: we pick the highest-category entry
+ (framework > service > tool > library) so the UI shows the most
+ interesting label.
+ """
+ result = await session.execute(
+ select(ExternalSystem).where(ExternalSystem.repository_id == repo_id)
+ )
+ rows = list(result.scalars())
+ priority = {"framework": 3, "service": 2, "tool": 1, "library": 0}
+ by_name: dict[str, ExternalSystem] = {}
+ for row in rows:
+ prev = by_name.get(row.name)
+ if prev is None or priority.get(row.category, 0) > priority.get(prev.category, 0):
+ by_name[row.name] = row
+
+ views: list[ExternalSystemView] = []
+ name_to_id: dict[str, str] = {}
+ for name in sorted(by_name):
+ row = by_name[name]
+ view_id = f"ext:{name}"
+ views.append(
+ ExternalSystemView(
+ id=view_id,
+ name=name,
+ display_name=row.display_name or name,
+ category=row.category,
+ ecosystem=row.ecosystem,
+ version=row.version,
+ )
+ )
+ name_to_id[name] = view_id
+ return views, name_to_id
+
+
+def _system_for(repo: Repository | None, repo_id: str) -> System:
+ if repo is None:
+ return System(id=f"sys:{repo_id}", name=repo_id)
+ return System(id=f"sys:{repo.id}", name=repo.name, description="")
+
+
+# ---------------------------------------------------------------------------
+# Builders
+# ---------------------------------------------------------------------------
+
+
+async def build_l1(session: AsyncSession, repo_id: str) -> C4L1:
+ repo = await _load_repo(session, repo_id)
+ system = _system_for(repo, repo_id)
+ externals, _ = await _external_views(session, repo_id)
+
+ # Default actor — Phase 1 of issue #203 keeps a single generic User.
+ person = Person(id="person:user", name="User", description="Uses the system")
+
+ relations: list[Relation] = [
+ Relation(source_id=person.id, target_id=system.id, label="uses")
+ ]
+ for ext in externals:
+ relations.append(
+ Relation(source_id=system.id, target_id=ext.id, label=ext.category)
+ )
+ return C4L1(
+ system=system,
+ people=[person],
+ external_systems=externals,
+ relations=relations,
+ )
+
+
+async def build_l2(session: AsyncSession, repo_id: str) -> C4L2:
+ containers = await detect_containers(session, repo_id)
+ externals, _ = await _external_views(session, repo_id)
+
+ file_to_container = await _file_to_container_map(session, repo_id, containers)
+ file_to_external = await external_node_to_system_id(session, repo_id)
+
+ relations = await aggregate_relations(
+ session,
+ repo_id,
+ file_to_box=file_to_container,
+ file_to_external=file_to_external,
+ )
+
+ # Only surface externals actually depended on by at least one container.
+ used_external_ids = {r.target_id for r in relations if r.target_id.startswith("ext:")}
+ pruned_externals = [e for e in externals if e.id in used_external_ids]
+ return C4L2(containers=containers, external_systems=pruned_externals, relations=relations)
+
+
+async def build_l3(session: AsyncSession, repo_id: str, container_id_value: str) -> C4L3 | None:
+ """Return L3 view for one container, or ``None`` if it doesn't exist."""
+ containers = await detect_containers(session, repo_id)
+ container = next((c for c in containers if c.id == container_id_value), None)
+ if container is None:
+ return None
+
+ components, in_container_index = await detect_components(
+ session, repo_id, container.path
+ )
+
+ # Files outside this container map to their owning container so cross-
+ # container edges show as component → other-container.
+ file_to_box: dict[str, str] = dict(in_container_index)
+ other_containers_index = await _file_to_container_map(
+ session,
+ repo_id,
+ [c for c in containers if c.id != container.id],
+ )
+ file_to_box.update(other_containers_index)
+
+ file_to_external = await external_node_to_system_id(session, repo_id)
+ relations = await aggregate_relations(
+ session,
+ repo_id,
+ file_to_box=file_to_box,
+ file_to_external=file_to_external,
+ )
+
+ relevant_box_ids = {c.id for c in components} | {container.id}
+ relations = [
+ r for r in relations
+ if r.source_id in relevant_box_ids or r.target_id in relevant_box_ids
+ ]
+
+ externals_all, _ = await _external_views(session, repo_id)
+ used_external_ids = {r.target_id for r in relations if r.target_id.startswith("ext:")}
+ used_external_ids |= {r.source_id for r in relations if r.source_id.startswith("ext:")}
+ externals = [e for e in externals_all if e.id in used_external_ids]
+
+ return C4L3(
+ container=container,
+ components=components,
+ external_systems=externals,
+ relations=relations,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+async def _file_to_container_map(
+ session: AsyncSession,
+ repo_id: str,
+ containers: list[Container],
+) -> dict[str, str]:
+ """Map every file path to its owning container id, longest-prefix wins."""
+ from repowise.core.persistence import GraphNode
+
+ result = await session.execute(
+ select(GraphNode.node_id).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "file",
+ )
+ )
+ paths = [row[0] for row in result.all()]
+ sorted_containers = sorted(containers, key=lambda c: len(c.path), reverse=True)
+ out: dict[str, str] = {}
+ bucket: dict[str, list[str]] = defaultdict(list)
+ for path in paths:
+ for c in sorted_containers:
+ if not c.path:
+ bucket[c.id].append(path)
+ out[path] = c.id
+ break
+ if path == c.path or path.startswith(c.path + "/"):
+ bucket[c.id].append(path)
+ out[path] = c.id
+ break
+ return out
diff --git a/packages/server/src/repowise/server/services/c4_builder/components.py b/packages/server/src/repowise/server/services/c4_builder/components.py
new file mode 100644
index 000000000..dbfc8b419
--- /dev/null
+++ b/packages/server/src/repowise/server/services/c4_builder/components.py
@@ -0,0 +1,117 @@
+"""Detect C4 L3 components inside a single container.
+
+A component is a top-level subdirectory of the container. Files that sit
+directly at the container root (no subdirectory) are bucketed into a
+synthetic ``_root`` component so the UI can render them without a
+"missing parent" gap.
+
+Returns the components plus a ``file_index`` mapping each file path inside
+the container to its owning component id — relations.py reuses this index
+to roll file→file edges up to component→component edges.
+"""
+
+from __future__ import annotations
+
+from collections import Counter, defaultdict
+
+from repowise.core.persistence import GraphNode
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from .containers import container_id
+from .models import Component
+
+ROOT_COMPONENT_NAME = "_root"
+
+
+def component_id(container_path: str, component_name: str) -> str:
+ base = container_path or "."
+ return f"cmp:{base}/{component_name}"
+
+
+async def detect_components(
+ session: AsyncSession,
+ repository_id: str,
+ container_path: str,
+) -> tuple[list[Component], dict[str, str]]:
+ """Return (components, file_index) for ``container_path``.
+
+ ``file_index`` maps every file path inside the container to the id of
+ the component that owns it.
+ """
+ file_nodes = await _files_in(session, repository_id, container_path)
+
+ bucket: dict[str, list[GraphNode]] = defaultdict(list)
+ for node in file_nodes:
+ comp = _component_name(node.node_id, container_path)
+ bucket[comp].append(node)
+
+ components: list[Component] = []
+ file_index: dict[str, str] = {}
+ cid = container_id(container_path)
+ for comp_name in sorted(bucket):
+ nodes = bucket[comp_name]
+ comp_path = f"{container_path}/{comp_name}" if container_path else comp_name
+ comp_id = component_id(container_path, comp_name)
+ components.append(
+ Component(
+ id=comp_id,
+ name=comp_name,
+ path=comp_path,
+ container_id=cid,
+ file_count=len(nodes),
+ symbol_count=sum(n.symbol_count or 0 for n in nodes),
+ )
+ )
+ for n in nodes:
+ file_index[n.node_id] = comp_id
+ return components, file_index
+
+
+def _component_name(file_path: str, container_path: str) -> str:
+ """Compute the top-level subdirectory of ``file_path`` relative to the
+ container root."""
+ if container_path:
+ rel = file_path[len(container_path) + 1 :] if file_path.startswith(container_path + "/") else file_path
+ else:
+ rel = file_path
+ if "/" in rel:
+ return rel.split("/", 1)[0]
+ return ROOT_COMPONENT_NAME
+
+
+async def _files_in(
+ session: AsyncSession, repository_id: str, container_path: str
+) -> list[GraphNode]:
+ stmt = select(GraphNode).where(
+ GraphNode.repository_id == repository_id,
+ GraphNode.node_type == "file",
+ )
+ if container_path:
+ prefix = container_path + "/"
+ # SQLite's LIKE is case-sensitive when the LHS is binary; for path
+ # matching that's the behaviour we want.
+ stmt = stmt.where(
+ (GraphNode.node_id == container_path) | GraphNode.node_id.like(prefix + "%")
+ )
+ result = await session.execute(stmt)
+ nodes = list(result.scalars())
+ if not container_path:
+ return nodes
+ # We may have over-selected files whose path simply starts with the
+ # container name as a prefix substring (e.g., "packages/core" should not
+ # capture "packages/core-extras/foo.py"). Final filter:
+ prefix = container_path + "/"
+ return [n for n in nodes if n.node_id == container_path or n.node_id.startswith(prefix)]
+
+
+# Re-export so callers can introspect / display the synthetic bucket name
+__all__ = ["ROOT_COMPONENT_NAME", "component_id", "detect_components"]
+
+
+# Convenience used by L2 relations: dominant language across the bucket.
+def dominant_language(nodes: list[GraphNode]) -> str:
+ counter: Counter[str] = Counter(
+ n.language for n in nodes if n.language and n.language != "unknown"
+ )
+ return counter.most_common(1)[0][0] if counter else "unknown"
diff --git a/packages/server/src/repowise/server/services/c4_builder/containers.py b/packages/server/src/repowise/server/services/c4_builder/containers.py
new file mode 100644
index 000000000..b21ee3072
--- /dev/null
+++ b/packages/server/src/repowise/server/services/c4_builder/containers.py
@@ -0,0 +1,128 @@
+"""Detect C4 L2 containers for an indexed repository.
+
+Strategy
+--------
+Containers are derived from the persisted ``external_systems`` table — every
+``declared_in`` path points at a manifest file, and that manifest's parent
+directory is a container root. This works for both monorepos (many manifests)
+and single-package repos (one root manifest).
+
+If no manifests were found (rare — exotic stacks), we fall back to the set
+of top-level directories that hold indexed files.
+
+Each container's ``language``, ``file_count``, and ``symbol_count`` are
+aggregated from ``graph_nodes`` rows whose ``node_id`` (file path) lives
+inside the container directory.
+"""
+
+from __future__ import annotations
+
+from collections import Counter, defaultdict
+from collections.abc import Iterable
+
+from repowise.core.persistence import ExternalSystem, GraphNode
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from .models import Container
+
+
+async def detect_containers(
+ session: AsyncSession, repository_id: str
+) -> list[Container]:
+ """Return the list of containers detected for ``repository_id``.
+
+ Stable ordering by ``path`` so the C4 diagram doesn't reshuffle between
+ requests.
+ """
+ container_roots = await _container_roots_from_manifests(session, repository_id)
+ file_nodes = await _file_nodes(session, repository_id)
+
+ if not container_roots:
+ container_roots = _top_level_dirs(node.node_id for node in file_nodes)
+
+ # Sort longest path first so nested manifests win over their parents.
+ sorted_roots = sorted(container_roots, key=len, reverse=True)
+
+ grouped: dict[str, list[GraphNode]] = defaultdict(list)
+ for node in file_nodes:
+ root = _match_container(node.node_id, sorted_roots)
+ if root is not None:
+ grouped[root].append(node)
+
+ containers: list[Container] = []
+ for root in sorted(grouped):
+ nodes = grouped[root]
+ lang = _dominant_language(nodes)
+ name = root.split("/")[-1] if root else "."
+ containers.append(
+ Container(
+ id=container_id(root),
+ name=name or ".",
+ path=root,
+ language=lang,
+ file_count=len(nodes),
+ symbol_count=sum(n.symbol_count or 0 for n in nodes),
+ )
+ )
+ return containers
+
+
+def container_id(path: str) -> str:
+ """Stable id for a container path. Edge sources/targets use this form."""
+ return f"pkg:{path}" if path else "pkg:."
+
+
+async def _container_roots_from_manifests(
+ session: AsyncSession, repository_id: str
+) -> set[str]:
+ """Return the unique parent directories of every declared manifest."""
+ result = await session.execute(
+ select(ExternalSystem.declared_in).where(
+ ExternalSystem.repository_id == repository_id
+ )
+ )
+ roots: set[str] = set()
+ for (declared_in,) in result.all():
+ if not declared_in:
+ continue
+ parent = declared_in.rsplit("/", 1)[0] if "/" in declared_in else ""
+ roots.add(parent)
+ return roots
+
+
+async def _file_nodes(session: AsyncSession, repository_id: str) -> list[GraphNode]:
+ result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repository_id,
+ GraphNode.node_type == "file",
+ )
+ )
+ return list(result.scalars())
+
+
+def _top_level_dirs(paths: Iterable[str]) -> set[str]:
+ out: set[str] = set()
+ for path in paths:
+ if "/" in path:
+ out.add(path.split("/", 1)[0])
+ else:
+ out.add("")
+ return out
+
+
+def _match_container(file_path: str, sorted_roots: list[str]) -> str | None:
+ """Return the deepest container root containing ``file_path``."""
+ for root in sorted_roots:
+ if not root:
+ return root # root manifest catches everything that isn't claimed
+ if file_path == root or file_path.startswith(root + "/"):
+ return root
+ return None
+
+
+def _dominant_language(nodes: list[GraphNode]) -> str:
+ counter: Counter[str] = Counter(
+ n.language for n in nodes if n.language and n.language != "unknown"
+ )
+ return counter.most_common(1)[0][0] if counter else "unknown"
diff --git a/packages/server/src/repowise/server/services/c4_builder/mermaid.py b/packages/server/src/repowise/server/services/c4_builder/mermaid.py
new file mode 100644
index 000000000..4d4ca4b81
--- /dev/null
+++ b/packages/server/src/repowise/server/services/c4_builder/mermaid.py
@@ -0,0 +1,126 @@
+"""Mermaid C4 emitters for L1 / L2 / L3 views.
+
+Consumes the same ``C4L1`` / ``C4L2`` / ``C4L3`` dataclasses the API serves,
+so there's a single source of truth for what a container or component is.
+
+Mermaid's C4 plugin syntax: https://mermaid.js.org/syntax/c4.html
+"""
+
+from __future__ import annotations
+
+import re
+
+from .models import C4L1, C4L2, C4L3, Container, ExternalSystemView
+
+
+_SAFE = re.compile(r"[^a-zA-Z0-9_]")
+
+
+def _sid(node_id: str) -> str:
+ """Mermaid identifiers must be alnum/underscore."""
+ return _SAFE.sub("_", node_id)
+
+
+def _q(text: str) -> str:
+ """Quote a label for Mermaid — escape embedded quotes."""
+ return text.replace('"', "'")
+
+
+def _ext_kind(cat: str) -> str:
+ """Map our category to a Mermaid C4 element type."""
+ if cat == "service":
+ return "System_Ext"
+ return "Container_Ext"
+
+
+def to_mermaid_l1(view: C4L1) -> str:
+ lines: list[str] = ["C4Context", f' title System Context — {_q(view.system.name)}', ""]
+
+ for person in view.people:
+ lines.append(
+ f' Person({_sid(person.id)}, "{_q(person.name)}", "{_q(person.description)}")'
+ )
+
+ lines.append(
+ f' System({_sid(view.system.id)}, "{_q(view.system.name)}", '
+ f'"{_q(view.system.description or "System under analysis")}")'
+ )
+
+ for ext in view.external_systems:
+ kind = _ext_kind(ext.category)
+ version = f" {ext.version}" if ext.version else ""
+ lines.append(
+ f' {kind}({_sid(ext.id)}, "{_q(ext.display_name)}", '
+ f'"{_q(ext.ecosystem + version)}")'
+ )
+
+ if view.relations:
+ lines.append("")
+ for rel in view.relations:
+ lines.append(_rel_line(rel.source_id, rel.target_id, rel.label))
+
+ return "\n".join(lines) + "\n"
+
+
+def to_mermaid_l2(view: C4L2, system_name: str) -> str:
+ lines: list[str] = ["C4Container", f' title Containers — {_q(system_name)}', ""]
+ lines.append(f' System_Boundary(sys, "{_q(system_name)}") {{')
+ for c in view.containers:
+ lines.append(_container_line(c, indent=" "))
+ lines.append(" }")
+
+ for ext in view.external_systems:
+ lines.append(_external_line(ext))
+
+ if view.relations:
+ lines.append("")
+ for rel in view.relations:
+ lines.append(_rel_line(rel.source_id, rel.target_id, rel.label))
+
+ return "\n".join(lines) + "\n"
+
+
+def to_mermaid_l3(view: C4L3, system_name: str) -> str:
+ lines: list[str] = [
+ "C4Component",
+ f' title Components — {_q(view.container.name)} ({_q(system_name)})',
+ "",
+ ]
+ lines.append(f' Container_Boundary({_sid(view.container.id)}, "{_q(view.container.name)}") {{')
+ for cmp in view.components:
+ lines.append(
+ f' Component({_sid(cmp.id)}, "{_q(cmp.name)}", '
+ f'"{cmp.file_count} files · {cmp.symbol_count} symbols", "{_q(cmp.path)}")'
+ )
+ lines.append(" }")
+
+ for ext in view.external_systems:
+ lines.append(_external_line(ext))
+
+ if view.relations:
+ lines.append("")
+ for rel in view.relations:
+ lines.append(_rel_line(rel.source_id, rel.target_id, rel.label))
+
+ return "\n".join(lines) + "\n"
+
+
+def _container_line(c: Container, indent: str = " ") -> str:
+ desc = f"{c.file_count} files · {c.symbol_count} symbols"
+ return (
+ f'{indent}Container({_sid(c.id)}, "{_q(c.name)}", '
+ f'"{_q(c.language)}", "{_q(desc)}")'
+ )
+
+
+def _external_line(ext: ExternalSystemView) -> str:
+ kind = _ext_kind(ext.category)
+ version = f" {ext.version}" if ext.version else ""
+ return (
+ f' {kind}({_sid(ext.id)}, "{_q(ext.display_name)}", '
+ f'"{_q(ext.ecosystem + version)}")'
+ )
+
+
+def _rel_line(source: str, target: str, label: str) -> str:
+ return f' Rel({_sid(source)}, {_sid(target)}, "{_q(label or "uses")}")'
diff --git a/packages/server/src/repowise/server/services/c4_builder/models.py b/packages/server/src/repowise/server/services/c4_builder/models.py
new file mode 100644
index 000000000..dac22330c
--- /dev/null
+++ b/packages/server/src/repowise/server/services/c4_builder/models.py
@@ -0,0 +1,105 @@
+"""Plain dataclasses produced by the C4 builder.
+
+These are framework-agnostic (no Pydantic, no SQLAlchemy) so the builder
+can be unit-tested without spinning up a session, and so a future Mermaid
+emitter can consume the same data structures.
+
+The server routers wrap these into Pydantic response models (see
+``server/schemas.py``); the conversion is mechanical.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+
+@dataclass(frozen=True)
+class Person:
+ id: str
+ name: str
+ description: str = ""
+
+
+@dataclass(frozen=True)
+class System:
+ """The 'system under design' — the indexed repo as a whole."""
+
+ id: str
+ name: str
+ description: str = ""
+
+
+@dataclass(frozen=True)
+class ExternalSystemView:
+ id: str # stable id used in edges; e.g., "ext:react"
+ name: str
+ display_name: str
+ category: str # framework | service | tool | library
+ ecosystem: str
+ version: str | None = None
+
+
+@dataclass(frozen=True)
+class Container:
+ """A deployable / runnable unit. Typically a workspace package, or a
+ top-level directory in a non-monorepo. ``path`` is repo-relative.
+ """
+
+ id: str # "pkg:packages/core"
+ name: str
+ path: str
+ language: str
+ file_count: int
+ symbol_count: int
+ hotspot_count: int = 0
+ dead_count: int = 0
+
+
+@dataclass(frozen=True)
+class Component:
+ """A sub-module inside a container — top-level child directory, or the
+ synthetic ``_root`` group for files at the container root.
+ """
+
+ id: str # "cmp:packages/core/ingestion"
+ name: str
+ path: str # repo-relative
+ container_id: str
+ file_count: int
+ symbol_count: int
+
+
+@dataclass(frozen=True)
+class Relation:
+ """A typed edge between any two C4 boxes (container ↔ container,
+ container ↔ external, component ↔ component, component ↔ external).
+ """
+
+ source_id: str
+ target_id: str
+ label: str = ""
+ edge_count: int = 1
+ edge_types: tuple[str, ...] = field(default_factory=tuple)
+
+
+@dataclass(frozen=True)
+class C4L1:
+ system: System
+ people: list[Person]
+ external_systems: list[ExternalSystemView]
+ relations: list[Relation]
+
+
+@dataclass(frozen=True)
+class C4L2:
+ containers: list[Container]
+ external_systems: list[ExternalSystemView]
+ relations: list[Relation]
+
+
+@dataclass(frozen=True)
+class C4L3:
+ container: Container
+ components: list[Component]
+ external_systems: list[ExternalSystemView]
+ relations: list[Relation]
diff --git a/packages/server/src/repowise/server/services/c4_builder/relations.py b/packages/server/src/repowise/server/services/c4_builder/relations.py
new file mode 100644
index 000000000..9edbca06d
--- /dev/null
+++ b/packages/server/src/repowise/server/services/c4_builder/relations.py
@@ -0,0 +1,105 @@
+"""Aggregate file→file graph edges up to container/component relations.
+
+The graph stores edges between individual files (and symbols). For C4
+diagrams we need edges between higher-level boxes — between containers at
+L2, between components at L3. This module does that aggregation:
+
+ 1. Load all ``graph_edges`` whose source AND target are file-level.
+ 2. Map each endpoint to its container (L2) or component (L3) using the
+ ``file_index`` produced by :mod:`.containers` / :mod:`.components`.
+ 3. Group by (source_box, target_box, edge_type) and sum counts.
+ 4. Drop self-loops — an edge from a container to itself is not useful
+ to a viewer.
+
+External-system edges are produced from file→``external:*`` edges where
+the target's ``external_system_id`` resolved to a row in the
+``external_systems`` table.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+
+from repowise.core.persistence import ExternalSystem, GraphEdge, GraphNode
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from .models import Relation
+
+
+async def aggregate_relations(
+ session: AsyncSession,
+ repository_id: str,
+ file_to_box: dict[str, str],
+ *,
+ file_to_external: dict[str, str] | None = None,
+) -> list[Relation]:
+ """Roll file→file edges up to box→box edges.
+
+ Parameters
+ ----------
+ file_to_box:
+ Map of file path → owning container/component id.
+ file_to_external:
+ Map of ``external:*`` node_id → external-system id (e.g., ``ext:react``).
+ When provided, edges whose target is an external node are also
+ emitted (as box → external).
+ """
+ file_to_external = file_to_external or {}
+ result = await session.execute(
+ select(GraphEdge.source_node_id, GraphEdge.target_node_id, GraphEdge.edge_type)
+ .where(GraphEdge.repository_id == repository_id)
+ )
+
+ counts: dict[tuple[str, str], int] = defaultdict(int)
+ types: dict[tuple[str, str], set[str]] = defaultdict(set)
+
+ for src, tgt, etype in result.all():
+ src_box = file_to_box.get(src)
+ if src_box is None:
+ continue
+ if tgt in file_to_box:
+ tgt_box = file_to_box[tgt]
+ elif tgt in file_to_external:
+ tgt_box = file_to_external[tgt]
+ else:
+ continue
+ if src_box == tgt_box:
+ continue
+ key = (src_box, tgt_box)
+ counts[key] += 1
+ types[key].add(etype or "imports")
+
+ relations: list[Relation] = []
+ for (src_box, tgt_box), count in counts.items():
+ etypes = tuple(sorted(types[(src_box, tgt_box)]))
+ label = etypes[0] if len(etypes) == 1 else f"{etypes[0]} +{len(etypes) - 1}"
+ relations.append(
+ Relation(
+ source_id=src_box,
+ target_id=tgt_box,
+ label=label,
+ edge_count=count,
+ edge_types=etypes,
+ )
+ )
+ relations.sort(key=lambda r: (-r.edge_count, r.source_id, r.target_id))
+ return relations
+
+
+async def external_node_to_system_id(
+ session: AsyncSession,
+ repository_id: str,
+) -> dict[str, str]:
+ """Map ``external:*`` graph_node ids to ``ext:<name>`` view ids.
+
+ Only nodes whose ``external_system_id`` resolved to an ExternalSystem
+ row are returned — anything else stays unmapped and is dropped by the
+ aggregator (it would be a noisy, unlabeled box otherwise).
+ """
+ result = await session.execute(
+ select(GraphNode.node_id, ExternalSystem.name)
+ .join(ExternalSystem, GraphNode.external_system_id == ExternalSystem.id)
+ .where(GraphNode.repository_id == repository_id)
+ )
+ return {node_id: f"ext:{name}" for node_id, name in result.all()}
diff --git a/packages/ui/__tests__/c4/layout.test.ts b/packages/ui/__tests__/c4/layout.test.ts
new file mode 100644
index 000000000..041a48575
--- /dev/null
+++ b/packages/ui/__tests__/c4/layout.test.ts
@@ -0,0 +1,53 @@
+import { describe, it, expect } from "vitest";
+import { computeC4Layout } from "../../src/c4/layout/elk-c4-layout";
+
+describe("computeC4Layout", () => {
+ it("returns empty map for empty input", async () => {
+ const positions = await computeC4Layout([], []);
+ expect(positions.size).toBe(0);
+ });
+
+ it("positions every input node", async () => {
+ const nodes = [
+ { id: "person:user", width: 140, height: 90 },
+ { id: "sys:demo", width: 220, height: 110 },
+ { id: "ext:fastapi", width: 180, height: 90 },
+ ];
+ const edges = [
+ { id: "e1", source: "person:user", target: "sys:demo" },
+ { id: "e2", source: "sys:demo", target: "ext:fastapi" },
+ ];
+ const positions = await computeC4Layout(nodes, edges);
+ expect(positions.size).toBe(3);
+ for (const n of nodes) {
+ const p = positions.get(n.id);
+ expect(p).toBeDefined();
+ expect(p!.width).toBe(n.width);
+ expect(p!.height).toBe(n.height);
+ }
+ });
+
+ it("drops edges with unknown endpoints and self-loops", async () => {
+ const nodes = [{ id: "a", width: 100, height: 50 }];
+ const edges = [
+ { id: "e1", source: "a", target: "ghost" },
+ { id: "e2", source: "a", target: "a" },
+ ];
+ const positions = await computeC4Layout(nodes, edges);
+ expect(positions.size).toBe(1);
+ expect(positions.has("a")).toBe(true);
+ });
+
+ it("lays out edges top-down (target below source)", async () => {
+ const nodes = [
+ { id: "top", width: 100, height: 50 },
+ { id: "bottom", width: 100, height: 50 },
+ ];
+ const positions = await computeC4Layout(nodes, [
+ { id: "e1", source: "top", target: "bottom" },
+ ]);
+ const top = positions.get("top")!;
+ const bottom = positions.get("bottom")!;
+ expect(bottom.y).toBeGreaterThan(top.y);
+ });
+});
diff --git a/packages/ui/__tests__/c4/store.test.ts b/packages/ui/__tests__/c4/store.test.ts
new file mode 100644
index 000000000..8d17ca8ce
--- /dev/null
+++ b/packages/ui/__tests__/c4/store.test.ts
@@ -0,0 +1,61 @@
+import { describe, it, expect } from "vitest";
+import { act, renderHook } from "@testing-library/react";
+import { useC4Store } from "../../src/c4/store/use-c4-store";
+
+describe("useC4Store", () => {
+ it("defaults to L2 with no container or selection", () => {
+ const { result } = renderHook(() => useC4Store());
+ expect(result.current.level).toBe(2);
+ expect(result.current.activeContainerId).toBeNull();
+ expect(result.current.selectedNodeId).toBeNull();
+ });
+
+ it("honors initialLevel and initialContainerId", () => {
+ const { result } = renderHook(() =>
+ useC4Store({ initialLevel: 3, initialContainerId: "pkg:packages/core" }),
+ );
+ expect(result.current.level).toBe(3);
+ expect(result.current.activeContainerId).toBe("pkg:packages/core");
+ });
+
+ it("drillIntoContainer moves to L3 and clears selection", () => {
+ const { result } = renderHook(() => useC4Store());
+ act(() => result.current.selectNode("pkg:foo"));
+ act(() => result.current.drillIntoContainer("pkg:packages/core"));
+ expect(result.current.level).toBe(3);
+ expect(result.current.activeContainerId).toBe("pkg:packages/core");
+ expect(result.current.selectedNodeId).toBeNull();
+ });
+
+ it("drillOut steps L3 → L2 → L1 and drops the container", () => {
+ const { result } = renderHook(() =>
+ useC4Store({ initialLevel: 3, initialContainerId: "pkg:x" }),
+ );
+ act(() => result.current.drillOut());
+ expect(result.current.level).toBe(2);
+ expect(result.current.activeContainerId).toBeNull();
+ act(() => result.current.drillOut());
+ expect(result.current.level).toBe(1);
+ act(() => result.current.drillOut()); // no-op at L1
+ expect(result.current.level).toBe(1);
+ });
+
+ it("setLevel(2) from L3 drops the active container", () => {
+ const { result } = renderHook(() =>
+ useC4Store({ initialLevel: 3, initialContainerId: "pkg:x" }),
+ );
+ act(() => result.current.setLevel(2));
+ expect(result.current.level).toBe(2);
+ expect(result.current.activeContainerId).toBeNull();
+ });
+
+ it("fires onChange on every transition", () => {
+ const calls: number[] = [];
+ const { result } = renderHook(() =>
+ useC4Store({ onChange: (s) => calls.push(s.level) }),
+ );
+ act(() => result.current.setLevel(1));
+ act(() => result.current.drillIntoContainer("pkg:a"));
+ expect(calls).toEqual([1, 3]);
+ });
+});
diff --git a/packages/ui/package.json b/packages/ui/package.json
index c3ccd1cb4..f0c7e2399 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -49,6 +49,9 @@
"./jobs/*": "./src/jobs/*.tsx",
"./blast-radius": "./src/blast-radius/index.ts",
"./blast-radius/*": "./src/blast-radius/*.tsx",
+ "./c4": "./src/c4/index.ts",
+ "./c4/export": "./src/c4/export/index.ts",
+ "./c4/*": "./src/c4/*.tsx",
"./costs": "./src/costs/index.ts",
"./costs/*": "./src/costs/*.tsx",
"./security": "./src/security/index.ts",
diff --git a/packages/ui/src/c4/C4Diagram.tsx b/packages/ui/src/c4/C4Diagram.tsx
new file mode 100644
index 000000000..6c698e90e
--- /dev/null
+++ b/packages/ui/src/c4/C4Diagram.tsx
@@ -0,0 +1,279 @@
+"use client";
+
+/**
+ * Top-level C4 diagram view.
+ *
+ * Pure presentational + interaction shell. The host page is responsible for
+ * fetching `l1View`/`l2View`/`l3View` (typically with SWR per level) and
+ * passing the active one in. State (level / active container / selection) is
+ * either lifted from the host via props OR managed locally via `useC4Store`.
+ */
+
+import { useCallback, useMemo, useState, type ReactNode } from "react";
+import {
+ Background,
+ Controls,
+ MiniMap,
+ ReactFlow,
+ ReactFlowProvider,
+ type Node,
+ type NodeMouseHandler,
+} from "@xyflow/react";
+import "@xyflow/react/dist/style.css";
+import { c4NodeTypes } from "./nodes";
+import { c4EdgeTypes } from "./edges/RelationEdge";
+import {
+ C4Breadcrumb,
+ C4Legend,
+ C4LevelTabs,
+ C4NodeInspector,
+} from "./panels";
+import { C4ExportMenu } from "./export/ExportMenu";
+import { useC4Layout } from "./hooks/use-c4-layout";
+import { useC4Keyboard } from "./hooks/use-c4-keyboard";
+import type {
+ C4L1,
+ C4L2,
+ C4L3,
+ C4Level,
+ C4NodeData,
+} from "./types";
+
+export interface C4DiagramProps {
+ level: C4Level;
+ activeContainerId: string | null;
+ systemName: string;
+
+ l1View: C4L1 | null;
+ l2View: C4L2 | null;
+ l3View: C4L3 | null;
+
+ loading?: boolean;
+ error?: Error | null;
+
+ /** Paths with a generated wiki page; flags a docs badge on matching nodes. */
+ docsPathSet?: ReadonlySet<string>;
+
+ /**
+ * Render the right-rail panel for the currently selected node. If omitted,
+ * the basic <C4NodeInspector> is used. Hosts pass this to inject docs,
+ * git activity, health, etc.
+ */
+ renderInspector?: (args: {
+ data: C4NodeData;
+ onClose: () => void;
+ onDrillIn?: ((containerId: string) => void) | undefined;
+ }) => ReactNode;
+
+ /**
+ * Host-provided Mermaid source fetcher for the current view. When supplied,
+ * the export menu shows "Copy / Download Mermaid". Omit to hide.
+ */
+ fetchMermaid?: (() => Promise<string>) | undefined;
+
+ onLevelChange: (level: C4Level) => void;
+ onDrillInto: (containerId: string) => void;
+ onDrillOut: () => void;
+}
+
+export function C4Diagram(props: C4DiagramProps) {
+ return (
+ <ReactFlowProvider>
+ <C4DiagramInner {...props} />
+ </ReactFlowProvider>
+ );
+}
+
+function C4DiagramInner({
+ level,
+ activeContainerId,
+ systemName,
+ l1View,
+ l2View,
+ l3View,
+ loading,
+ error,
+ docsPathSet,
+ renderInspector,
+ fetchMermaid,
+ onLevelChange,
+ onDrillInto,
+ onDrillOut,
+}: C4DiagramProps) {
+ const view = level === 1 ? l1View : level === 2 ? l2View : l3View;
+ const layoutOpts = useMemo(() => (docsPathSet ? { docsPathSet } : {}), [docsPathSet]);
+ const { nodes, edges, loading: layoutLoading } = useC4Layout(level, view, layoutOpts);
+
+ const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
+ const selectedNode = useMemo(
+ () => (selectedNodeId ? nodes.find((n) => n.id === selectedNodeId) ?? null : null),
+ [nodes, selectedNodeId],
+ );
+ const selectedData = (selectedNode?.data as unknown as C4NodeData | undefined) ?? null;
+
+ useC4Keyboard(useCallback(() => {
+ if (selectedNodeId) {
+ setSelectedNodeId(null);
+ } else {
+ onDrillOut();
+ }
+ }, [onDrillOut, selectedNodeId]));
+
+ const handleNodeClick: NodeMouseHandler = useCallback((_, node) => {
+ setSelectedNodeId((cur) => (cur === node.id ? null : node.id));
+ }, []);
+
+ const handleNodeDoubleClick: NodeMouseHandler = useCallback(
+ (_, node: Node) => {
+ const data = node.data as unknown as C4NodeData;
+ if (data.kind === "container") {
+ onDrillInto(data.container.id);
+ setSelectedNodeId(null);
+ }
+ },
+ [onDrillInto],
+ );
+
+ const activeContainerPath = useMemo(() => {
+ if (level !== 3 || !activeContainerId) return null;
+ if (l3View?.container.id === activeContainerId) return l3View.container.path;
+ const found = l2View?.containers.find((c) => c.id === activeContainerId);
+ return found?.path ?? activeContainerId.replace(/^pkg:/, "");
+ }, [activeContainerId, l2View, l3View, level]);
+
+ const isLoading = loading || layoutLoading;
+
+ return (
+ <div
+ style={{
+ position: "relative",
+ width: "100%",
+ height: "100%",
+ display: "flex",
+ flexDirection: "column",
+ background: "var(--color-bg-canvas, #0b1220)",
+ }}
+ >
+ {/* Toolbar row */}
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 16,
+ padding: "8px 12px",
+ borderBottom: "1px solid var(--color-border-default, #334155)",
+ background: "var(--color-bg-surface, rgba(15,23,42,0.6))",
+ }}
+ >
+ <C4LevelTabs
+ level={level}
+ onLevelChange={onLevelChange}
+ l3Enabled={activeContainerId != null || level === 3}
+ />
+ <div style={{ width: 1, height: 20, background: "var(--color-border-default, #334155)" }} />
+ <C4Breadcrumb
+ level={level}
+ systemName={systemName}
+ activeContainerPath={activeContainerPath}
+ onNavigate={onLevelChange}
+ />
+ <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 12 }}>
+ <C4Legend />
+ <C4ExportMenu
+ nodes={nodes}
+ edges={edges}
+ fileNameStem={exportFileStem(systemName, level, activeContainerPath)}
+ title={exportTitle(systemName, level, activeContainerPath)}
+ disabled={nodes.length === 0}
+ {...(fetchMermaid ? { fetchMermaid } : {})}
+ />
+ </div>
+ </div>
+
+ {/* Canvas */}
+ <div style={{ position: "relative", flex: 1, minHeight: 0 }}>
+ {error && <CenteredMessage tone="error" text={error.message} />}
+ {!error && isLoading && nodes.length === 0 && (
+ <CenteredMessage tone="info" text="Loading C4 view…" />
+ )}
+ {!error && !isLoading && nodes.length === 0 && (
+ <CenteredMessage tone="empty" text="Nothing to show at this level." />
+ )}
+
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ nodeTypes={c4NodeTypes}
+ edgeTypes={c4EdgeTypes}
+ onNodeClick={handleNodeClick}
+ onNodeDoubleClick={handleNodeDoubleClick}
+ fitView
+ fitViewOptions={{ padding: 0.15 }}
+ minZoom={0.2}
+ maxZoom={2.5}
+ proOptions={{ hideAttribution: true }}
+ nodesDraggable={false}
+ nodesConnectable={false}
+ >
+ <Background gap={28} size={1} color="rgba(148,163,184,0.18)" />
+ <Controls showInteractive={false} />
+ <MiniMap pannable zoomable maskColor="rgba(11,18,32,0.85)" />
+ </ReactFlow>
+
+ {selectedData && renderInspector
+ ? renderInspector({
+ data: selectedData,
+ onClose: () => setSelectedNodeId(null),
+ onDrillIn: selectedData.kind === "container" ? onDrillInto : undefined,
+ })
+ : (
+ <C4NodeInspector
+ data={selectedData}
+ onClose={() => setSelectedNodeId(null)}
+ {...(selectedData?.kind === "container" ? { onDrillIn: onDrillInto } : {})}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+function exportTitle(systemName: string, level: C4Level, activePath: string | null): string {
+ if (level === 1) return `${systemName} — System Context`;
+ if (level === 2) return `${systemName} — Containers`;
+ return `${systemName} — Components${activePath ? ` (${activePath})` : ""}`;
+}
+
+function exportFileStem(systemName: string, level: C4Level, activePath: string | null): string {
+ const safe = (s: string) => s.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
+ const base = `${safe(systemName)}-c4-l${level}`;
+ if (level === 3 && activePath) return `${base}-${safe(activePath)}`;
+ return base;
+}
+
+function CenteredMessage({ tone, text }: { tone: "info" | "empty" | "error"; text: string }) {
+ const color =
+ tone === "error"
+ ? "#fca5a5"
+ : tone === "empty"
+ ? "var(--color-text-tertiary, #64748b)"
+ : "var(--color-text-secondary, #94a3b8)";
+ return (
+ <div
+ role="status"
+ style={{
+ position: "absolute",
+ inset: 0,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color,
+ fontSize: 13,
+ pointerEvents: "none",
+ zIndex: 3,
+ }}
+ >
+ {text}
+ </div>
+ );
+}
diff --git a/packages/ui/src/c4/edges/RelationEdge.tsx b/packages/ui/src/c4/edges/RelationEdge.tsx
new file mode 100644
index 000000000..24a1bf79d
--- /dev/null
+++ b/packages/ui/src/c4/edges/RelationEdge.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+/**
+ * Styled C4 relation edge — a bezier line with an optional label pill
+ * showing edge count and dominant edge type.
+ */
+
+import { memo } from "react";
+import {
+ BaseEdge,
+ EdgeLabelRenderer,
+ getBezierPath,
+ type EdgeProps,
+} from "@xyflow/react";
+import type { C4EdgeData } from "../types";
+
+function RelationEdgeImpl(props: EdgeProps) {
+ const {
+ id,
+ sourceX,
+ sourceY,
+ targetX,
+ targetY,
+ sourcePosition,
+ targetPosition,
+ markerEnd,
+ data,
+ selected,
+ } = props;
+ const relation = (data as C4EdgeData | undefined)?.relation;
+
+ const [edgePath, labelX, labelY] = getBezierPath({
+ sourceX,
+ sourceY,
+ sourcePosition,
+ targetX,
+ targetY,
+ targetPosition,
+ });
+
+ const stroke = selected ? "#fbbf24" : "#94a3b8";
+ const strokeWidth = relation && relation.edge_count > 5 ? 2 : 1.25;
+
+ const label = relation
+ ? relation.label ||
+ (relation.edge_count > 1
+ ? `${relation.edge_count} ${relation.edge_types[0] ?? "calls"}`
+ : (relation.edge_types[0] ?? ""))
+ : "";
+
+ return (
+ <>
+ <BaseEdge id={id} path={edgePath} {...(markerEnd ? { markerEnd } : {})} style={{ stroke, strokeWidth }} />
+ {label && (
+ <EdgeLabelRenderer>
+ <div
+ style={{
+ position: "absolute",
+ transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,
+ background: "rgba(15, 23, 42, 0.92)",
+ color: "#e2e8f0",
+ padding: "2px 6px",
+ borderRadius: 4,
+ fontSize: 10,
+ fontWeight: 500,
+ pointerEvents: "none",
+ border: "1px solid rgba(148, 163, 184, 0.25)",
+ whiteSpace: "nowrap",
+ }}
+ className="nodrag nopan"
+ >
+ {label}
+ </div>
+ </EdgeLabelRenderer>
+ )}
+ </>
+ );
+}
+
+export const RelationEdge = memo(RelationEdgeImpl);
+
+export const c4EdgeTypes = {
+ relation: RelationEdge,
+};
diff --git a/packages/ui/src/c4/export/ExportMenu.tsx b/packages/ui/src/c4/export/ExportMenu.tsx
new file mode 100644
index 000000000..a9b4bc18b
--- /dev/null
+++ b/packages/ui/src/c4/export/ExportMenu.tsx
@@ -0,0 +1,227 @@
+"use client";
+
+/**
+ * Toolbar dropdown to export the current C4 view as SVG, PNG, or Mermaid.
+ *
+ * SVG/PNG are built locally from the React Flow layout (svg-exporter +
+ * png-exporter). Mermaid is fetched from the host because the backend has
+ * the authoritative C4 source — keeps the diagram view and copy-as-mermaid
+ * output in sync.
+ */
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { Download, FileImage, FileType2, Copy, Check } from "lucide-react";
+import type { Edge, Node as FlowNode } from "@xyflow/react";
+import { buildC4Svg, downloadSvg } from "./svg-exporter";
+import { downloadPng } from "./png-exporter";
+
+export interface C4ExportMenuProps {
+ nodes: FlowNode[];
+ edges: Edge[];
+ /** Used in the SVG title bar + as the download filename stem. */
+ fileNameStem: string;
+ /** Optional title rendered into the exported SVG/PNG. */
+ title?: string;
+ /** Host-provided fetcher for the Mermaid source. Hidden if omitted. */
+ fetchMermaid?: () => Promise<string>;
+ /** Disabled when the diagram is empty / still loading. */
+ disabled?: boolean;
+}
+
+type Status = "idle" | "working" | "copied" | "error";
+
+export function C4ExportMenu({
+ nodes,
+ edges,
+ fileNameStem,
+ title,
+ fetchMermaid,
+ disabled,
+}: C4ExportMenuProps) {
+ const [open, setOpen] = useState(false);
+ const [status, setStatus] = useState<Status>("idle");
+ const rootRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ const handler = (event: MouseEvent) => {
+ if (!rootRef.current?.contains(event.target as globalThis.Node)) setOpen(false);
+ };
+ window.addEventListener("mousedown", handler);
+ return () => window.removeEventListener("mousedown", handler);
+ }, [open]);
+
+ const buildSvg = useCallback(
+ () => buildC4Svg(nodes, edges, title ? { title } : {}),
+ [nodes, edges, title],
+ );
+
+ const onSvg = useCallback(() => {
+ downloadSvg(buildSvg(), `${fileNameStem}.svg`);
+ setOpen(false);
+ }, [buildSvg, fileNameStem]);
+
+ const onPng = useCallback(async () => {
+ setStatus("working");
+ try {
+ await downloadPng(buildSvg(), `${fileNameStem}.png`, { scale: 2 });
+ setStatus("idle");
+ setOpen(false);
+ } catch {
+ setStatus("error");
+ }
+ }, [buildSvg, fileNameStem]);
+
+ const onMermaid = useCallback(async () => {
+ if (!fetchMermaid) return;
+ setStatus("working");
+ try {
+ const text = await fetchMermaid();
+ await navigator.clipboard.writeText(text);
+ setStatus("copied");
+ setTimeout(() => setStatus("idle"), 1500);
+ } catch {
+ setStatus("error");
+ }
+ }, [fetchMermaid]);
+
+ const onMermaidDownload = useCallback(async () => {
+ if (!fetchMermaid) return;
+ setStatus("working");
+ try {
+ const text = await fetchMermaid();
+ const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `${fileNameStem}.mmd`;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+ setStatus("idle");
+ setOpen(false);
+ } catch {
+ setStatus("error");
+ }
+ }, [fetchMermaid, fileNameStem]);
+
+ return (
+ <div ref={rootRef} style={{ position: "relative" }}>
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ disabled={disabled}
+ aria-haspopup="menu"
+ aria-expanded={open}
+ title="Export diagram"
+ style={{
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 6,
+ padding: "4px 10px",
+ fontSize: 11,
+ fontWeight: 500,
+ color: "var(--color-text-secondary, #cbd5e1)",
+ background: "transparent",
+ border: "1px solid var(--color-border-default, #334155)",
+ borderRadius: 4,
+ cursor: disabled ? "not-allowed" : "pointer",
+ opacity: disabled ? 0.5 : 1,
+ }}
+ >
+ <Download size={12} />
+ Export
+ </button>
+ {open && (
+ <div
+ role="menu"
+ style={{
+ position: "absolute",
+ top: "calc(100% + 4px)",
+ right: 0,
+ minWidth: 200,
+ background: "var(--color-bg-elevated, #111827)",
+ border: "1px solid var(--color-border-default, #334155)",
+ borderRadius: 6,
+ boxShadow: "0 10px 30px rgba(0,0,0,0.4)",
+ padding: 4,
+ zIndex: 10,
+ }}
+ >
+ <MenuItem icon={<FileImage size={12} />} label="Download SVG" onClick={onSvg} />
+ <MenuItem icon={<FileImage size={12} />} label="Download PNG (2×)" onClick={onPng} />
+ {fetchMermaid && (
+ <>
+ <Divider />
+ <MenuItem
+ icon={status === "copied" ? <Check size={12} /> : <Copy size={12} />}
+ label={status === "copied" ? "Copied" : "Copy as Mermaid"}
+ onClick={onMermaid}
+ />
+ <MenuItem
+ icon={<FileType2 size={12} />}
+ label="Download Mermaid (.mmd)"
+ onClick={onMermaidDownload}
+ />
+ </>
+ )}
+ {status === "error" && (
+ <div style={{ padding: "6px 10px", fontSize: 10, color: "#fca5a5" }}>
+ Export failed. Try again.
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function MenuItem({
+ icon,
+ label,
+ onClick,
+}: {
+ icon: React.ReactNode;
+ label: string;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ role="menuitem"
+ onClick={onClick}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ width: "100%",
+ padding: "6px 10px",
+ background: "transparent",
+ border: "none",
+ color: "var(--color-text-primary, #f1f5f9)",
+ fontSize: 12,
+ textAlign: "left",
+ cursor: "pointer",
+ borderRadius: 4,
+ }}
+ onMouseEnter={(e) => (e.currentTarget.style.background = "rgba(148,163,184,0.12)")}
+ onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
+ >
+ {icon}
+ {label}
+ </button>
+ );
+}
+
+function Divider() {
+ return (
+ <div
+ style={{
+ height: 1,
+ background: "var(--color-border-default, #334155)",
+ margin: "4px 2px",
+ }}
+ />
+ );
+}
diff --git a/packages/ui/src/c4/export/index.ts b/packages/ui/src/c4/export/index.ts
new file mode 100644
index 000000000..26ff47bc0
--- /dev/null
+++ b/packages/ui/src/c4/export/index.ts
@@ -0,0 +1,6 @@
+export { buildC4Svg, downloadSvg, triggerDownload } from "./svg-exporter";
+export type { SvgExportOptions } from "./svg-exporter";
+export { svgToPngBlob, downloadPng } from "./png-exporter";
+export type { PngExportOptions } from "./png-exporter";
+export { C4ExportMenu } from "./ExportMenu";
+export type { C4ExportMenuProps } from "./ExportMenu";
diff --git a/packages/ui/src/c4/export/png-exporter.ts b/packages/ui/src/c4/export/png-exporter.ts
new file mode 100644
index 000000000..a5c8a2581
--- /dev/null
+++ b/packages/ui/src/c4/export/png-exporter.ts
@@ -0,0 +1,64 @@
+/**
+ * Rasterize an SVG string to PNG via the browser's Image + canvas pipeline.
+ * Resolves to a Blob the caller can hand to `triggerDownload`.
+ */
+
+import { triggerDownload } from "./svg-exporter";
+
+export interface PngExportOptions {
+ /** Pixel ratio multiplier for higher-resolution output. Default 2. */
+ scale?: number;
+ /** Background fill applied if SVG has transparency. Default null (keep). */
+ background?: string | null;
+}
+
+export async function svgToPngBlob(
+ svg: string,
+ options: PngExportOptions = {},
+): Promise<Blob> {
+ const scale = options.scale ?? 2;
+ const blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
+ const url = URL.createObjectURL(blob);
+ try {
+ const img = await loadImage(url);
+ const width = img.naturalWidth || 1200;
+ const height = img.naturalHeight || 800;
+ const canvas = document.createElement("canvas");
+ canvas.width = Math.round(width * scale);
+ canvas.height = Math.round(height * scale);
+ const ctx = canvas.getContext("2d");
+ if (!ctx) throw new Error("2D canvas context unavailable");
+ if (options.background) {
+ ctx.fillStyle = options.background;
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ }
+ ctx.scale(scale, scale);
+ ctx.drawImage(img, 0, 0, width, height);
+ return await new Promise<Blob>((resolve, reject) => {
+ canvas.toBlob(
+ (out) => (out ? resolve(out) : reject(new Error("PNG encoding failed"))),
+ "image/png",
+ );
+ });
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+}
+
+export async function downloadPng(
+ svg: string,
+ filename: string,
+ options?: PngExportOptions,
+): Promise<void> {
+ const blob = await svgToPngBlob(svg, options);
+ triggerDownload(blob, filename);
+}
+
+function loadImage(src: string): Promise<HTMLImageElement> {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ img.onload = () => resolve(img);
+ img.onerror = () => reject(new Error("Failed to load SVG for rasterization"));
+ img.src = src;
+ });
+}
diff --git a/packages/ui/src/c4/export/svg-exporter.ts b/packages/ui/src/c4/export/svg-exporter.ts
new file mode 100644
index 000000000..4827e8235
--- /dev/null
+++ b/packages/ui/src/c4/export/svg-exporter.ts
@@ -0,0 +1,246 @@
+/**
+ * Build a clean, standalone SVG string from the C4 React Flow nodes + edges.
+ *
+ * We don't screenshot the DOM — we re-render the same layout positions into
+ * native SVG primitives. That keeps the file small, vector-perfect, and
+ * independent of whatever fonts or CSS happen to be on the page.
+ */
+
+import type { Edge, Node } from "@xyflow/react";
+import type { C4EdgeData, C4NodeData } from "../types";
+
+const TONE_STYLES = {
+ system: { bg: "#1f3a8a", border: "#1e40af", band: "#1e40af", text: "#ffffff" },
+ person: { bg: "#374151", border: "#4b5563", band: "#4b5563", text: "#ffffff" },
+ external: { bg: "#1f2937", border: "#374151", band: "#374151", text: "#e5e7eb" },
+ container: { bg: "#0f3a5f", border: "#1d4ed8", band: "#1d4ed8", text: "#ffffff" },
+ component: { bg: "#0d2a47", border: "#1e3a8a", band: "#1e3a8a", text: "#e5e7eb" },
+} as const;
+
+type Tone = keyof typeof TONE_STYLES;
+
+const PADDING = 40;
+const BAND_HEIGHT = 18;
+const FONT_FAMILY = "system-ui, -apple-system, Segoe UI, sans-serif";
+
+function escapeXml(value: string): string {
+ return value
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;")
+ .replace(/'/g, "&apos;");
+}
+
+function nodeTone(data: C4NodeData): Tone {
+ return data.kind;
+}
+
+function nodeTitle(data: C4NodeData): string {
+ switch (data.kind) {
+ case "system": return data.system.name;
+ case "person": return data.person.name;
+ case "external": return data.external.display_name || data.external.name;
+ case "container": return data.container.name === "_root" ? "(root)" : data.container.name;
+ case "component": return data.component.name === "_root" ? "(root)" : data.component.name;
+ }
+}
+
+function nodeSubtitle(data: C4NodeData): string | null {
+ switch (data.kind) {
+ case "system": return data.system.description || null;
+ case "person": return data.person.description || null;
+ case "external": return `${data.external.ecosystem} · ${data.external.category}`;
+ case "container": return data.container.path;
+ case "component": return data.component.path;
+ }
+}
+
+function nodeFooter(data: C4NodeData): string | null {
+ if (data.kind === "container") {
+ return `${data.container.file_count} files · ${data.container.symbol_count} symbols`;
+ }
+ if (data.kind === "component") {
+ return `${data.component.file_count} files · ${data.component.symbol_count} symbols`;
+ }
+ return null;
+}
+
+function truncate(text: string, max: number): string {
+ return text.length <= max ? text : text.slice(0, Math.max(0, max - 1)) + "…";
+}
+
+function nodeKindLabel(data: C4NodeData): string {
+ return data.kind.toUpperCase();
+}
+
+interface Bounds {
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+}
+
+function computeBounds(nodes: Node[]): Bounds {
+ if (nodes.length === 0) {
+ return { minX: 0, minY: 0, maxX: 800, maxY: 600 };
+ }
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ for (const n of nodes) {
+ const w = (n.width as number | undefined) ?? 200;
+ const h = (n.height as number | undefined) ?? 100;
+ minX = Math.min(minX, n.position.x);
+ minY = Math.min(minY, n.position.y);
+ maxX = Math.max(maxX, n.position.x + w);
+ maxY = Math.max(maxY, n.position.y + h);
+ }
+ return { minX, minY, maxX, maxY };
+}
+
+function renderNode(n: Node): string {
+ const data = n.data as unknown as C4NodeData;
+ const tone = nodeTone(data);
+ const style = TONE_STYLES[tone];
+ const w = (n.width as number | undefined) ?? 200;
+ const h = (n.height as number | undefined) ?? 100;
+ const x = n.position.x;
+ const y = n.position.y;
+
+ const title = escapeXml(truncate(nodeTitle(data), Math.floor(w / 8)));
+ const subtitle = nodeSubtitle(data);
+ const footer = nodeFooter(data);
+ const kind = escapeXml(nodeKindLabel(data));
+
+ const parts: string[] = [];
+ parts.push(`<g transform="translate(${x},${y})">`);
+ // box
+ parts.push(
+ `<rect width="${w}" height="${h}" rx="8" ry="8" fill="${style.bg}" stroke="${style.border}" stroke-width="1.5"/>`,
+ );
+ // header band
+ parts.push(
+ `<rect width="${w}" height="${BAND_HEIGHT}" rx="8" ry="8" fill="${style.band}"/>`,
+ );
+ // squared bottom of band
+ parts.push(
+ `<rect y="${BAND_HEIGHT - 8}" width="${w}" height="8" fill="${style.band}"/>`,
+ );
+ parts.push(
+ `<text x="8" y="${BAND_HEIGHT - 5}" font-family="${FONT_FAMILY}" font-size="9" font-weight="600" letter-spacing="0.6" fill="${style.text}" opacity="0.85">${kind}</text>`,
+ );
+ // title
+ parts.push(
+ `<text x="10" y="${BAND_HEIGHT + 20}" font-family="${FONT_FAMILY}" font-size="13" font-weight="600" fill="${style.text}">${title}</text>`,
+ );
+ if (subtitle) {
+ parts.push(
+ `<text x="10" y="${BAND_HEIGHT + 36}" font-family="${FONT_FAMILY}" font-size="11" fill="${style.text}" opacity="0.75">${escapeXml(truncate(subtitle, Math.floor(w / 6)))}</text>`,
+ );
+ }
+ if (footer) {
+ parts.push(
+ `<text x="10" y="${h - 8}" font-family="${FONT_FAMILY}" font-size="10" fill="${style.text}" opacity="0.8">${escapeXml(truncate(footer, Math.floor(w / 6)))}</text>`,
+ );
+ }
+ parts.push(`</g>`);
+ return parts.join("");
+}
+
+function nodeCenter(n: Node): { x: number; y: number; w: number; h: number } {
+ const w = (n.width as number | undefined) ?? 200;
+ const h = (n.height as number | undefined) ?? 100;
+ return { x: n.position.x + w / 2, y: n.position.y + h / 2, w, h };
+}
+
+function renderEdge(e: Edge, nodesById: Map<string, Node>): string {
+ const source = nodesById.get(e.source);
+ const target = nodesById.get(e.target);
+ if (!source || !target) return "";
+ const s = nodeCenter(source);
+ const t = nodeCenter(target);
+ // attach to closest horizontal edge
+ const sy = t.y > s.y ? s.y + s.h / 2 : s.y - s.h / 2;
+ const ty = t.y > s.y ? t.y - t.h / 2 : t.y + t.h / 2;
+ const sx = s.x;
+ const tx = t.x;
+ const midY = (sy + ty) / 2;
+ const path = `M ${sx} ${sy} C ${sx} ${midY}, ${tx} ${midY}, ${tx} ${ty}`;
+
+ const data = e.data as unknown as C4EdgeData | undefined;
+ const label = data?.relation?.label?.trim() ?? "";
+
+ const parts: string[] = [];
+ parts.push(
+ `<path d="${path}" fill="none" stroke="#475569" stroke-width="1.2" marker-end="url(#c4-arrow)"/>`,
+ );
+ if (label) {
+ const lx = (sx + tx) / 2;
+ const ly = midY;
+ const text = escapeXml(truncate(label, 32));
+ const padW = text.length * 6 + 10;
+ parts.push(
+ `<rect x="${lx - padW / 2}" y="${ly - 9}" width="${padW}" height="16" rx="3" fill="rgba(15,23,42,0.85)" stroke="#334155" stroke-width="0.5"/>`,
+ );
+ parts.push(
+ `<text x="${lx}" y="${ly + 3}" font-family="${FONT_FAMILY}" font-size="10" fill="#cbd5e1" text-anchor="middle">${text}</text>`,
+ );
+ }
+ return parts.join("");
+}
+
+export interface SvgExportOptions {
+ /** Optional title baked into the SVG header. */
+ title?: string;
+}
+
+export function buildC4Svg(
+ nodes: Node[],
+ edges: Edge[],
+ options: SvgExportOptions = {},
+): string {
+ const bounds = computeBounds(nodes);
+ const width = bounds.maxX - bounds.minX + PADDING * 2;
+ const height = bounds.maxY - bounds.minY + PADDING * 2 + (options.title ? 28 : 0);
+ const titleOffset = options.title ? 28 : 0;
+ const tx = -bounds.minX + PADDING;
+ const ty = -bounds.minY + PADDING + titleOffset;
+
+ const nodesById = new Map(nodes.map((n) => [n.id, n]));
+
+ const edgeMarkup = edges.map((e) => renderEdge(e, nodesById)).join("");
+ const nodeMarkup = nodes.map(renderNode).join("");
+
+ return `<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" width="${Math.round(width)}" height="${Math.round(height)}" viewBox="0 0 ${Math.round(width)} ${Math.round(height)}">
+ <defs>
+ <marker id="c4-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
+ <path d="M 0 0 L 10 5 L 0 10 z" fill="#475569"/>
+ </marker>
+ </defs>
+ <rect width="100%" height="100%" fill="#0b1220"/>
+ ${options.title ? `<text x="${PADDING}" y="22" font-family="${FONT_FAMILY}" font-size="14" font-weight="600" fill="#e5e7eb">${escapeXml(options.title)}</text>` : ""}
+ <g transform="translate(${tx},${ty})">
+ ${edgeMarkup}
+ ${nodeMarkup}
+ </g>
+</svg>`;
+}
+
+export function downloadSvg(svg: string, filename: string): void {
+ const blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
+ triggerDownload(blob, filename);
+}
+
+export function triggerDownload(blob: Blob, filename: string): void {
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+}
diff --git a/packages/ui/src/c4/hooks/use-c4-keyboard.ts b/packages/ui/src/c4/hooks/use-c4-keyboard.ts
new file mode 100644
index 000000000..5a6acc2b7
--- /dev/null
+++ b/packages/ui/src/c4/hooks/use-c4-keyboard.ts
@@ -0,0 +1,18 @@
+"use client";
+
+import { useEffect } from "react";
+
+/** Esc drills out one level. Bound globally; bail if focus is in an input. */
+export function useC4Keyboard(onEscape: () => void): void {
+ useEffect(() => {
+ function handler(e: KeyboardEvent) {
+ if (e.key !== "Escape") return;
+ const t = e.target as HTMLElement | null;
+ const tag = t?.tagName;
+ if (tag === "INPUT" || tag === "TEXTAREA" || (t && t.isContentEditable)) return;
+ onEscape();
+ }
+ window.addEventListener("keydown", handler);
+ return () => window.removeEventListener("keydown", handler);
+ }, [onEscape]);
+}
diff --git a/packages/ui/src/c4/hooks/use-c4-layout.ts b/packages/ui/src/c4/hooks/use-c4-layout.ts
new file mode 100644
index 000000000..1758fd6c7
--- /dev/null
+++ b/packages/ui/src/c4/hooks/use-c4-layout.ts
@@ -0,0 +1,185 @@
+"use client";
+
+/**
+ * Compute React Flow nodes + edges for a given C4 view.
+ *
+ * Pure transform from backend payload → React Flow inputs, threaded through
+ * the async ELK layout call. Memoized so a level switch or selection change
+ * doesn't re-layout.
+ */
+
+import { useEffect, useState } from "react";
+import type { Edge, Node } from "@xyflow/react";
+import {
+ C4_NODE_SIZES,
+ computeC4Layout,
+ type C4LayoutNode,
+} from "../layout/elk-c4-layout";
+import type {
+ C4EdgeData,
+ C4L1,
+ C4L2,
+ C4L3,
+ C4Level,
+ C4NodeData,
+ C4Relation,
+} from "../types";
+
+interface BuiltInputs {
+ nodes: { id: string; type: keyof typeof C4_NODE_SIZES; data: C4NodeData }[];
+ edges: { id: string; source: string; target: string; relation: C4Relation }[];
+}
+
+function buildL1(view: C4L1): BuiltInputs {
+ return {
+ nodes: [
+ ...view.people.map((p) => ({
+ id: p.id,
+ type: "person" as const,
+ data: { kind: "person" as const, person: p },
+ })),
+ {
+ id: view.system.id,
+ type: "system" as const,
+ data: { kind: "system" as const, system: view.system },
+ },
+ ...view.external_systems.map((e) => ({
+ id: e.id,
+ type: "external" as const,
+ data: { kind: "external" as const, external: e },
+ })),
+ ],
+ edges: view.relations.map((r, i) => ({
+ id: `e${i}:${r.source_id}->${r.target_id}`,
+ source: r.source_id,
+ target: r.target_id,
+ relation: r,
+ })),
+ };
+}
+
+function buildL2(view: C4L2, docsPathSet?: ReadonlySet<string>): BuiltInputs {
+ return {
+ nodes: [
+ ...view.containers.map((c) => ({
+ id: c.id,
+ type: "container" as const,
+ data: {
+ kind: "container" as const,
+ container: c,
+ hasDocs: docsPathSet?.has(c.path) ?? false,
+ },
+ })),
+ ...view.external_systems.map((e) => ({
+ id: e.id,
+ type: "external" as const,
+ data: { kind: "external" as const, external: e },
+ })),
+ ],
+ edges: view.relations.map((r, i) => ({
+ id: `e${i}:${r.source_id}->${r.target_id}`,
+ source: r.source_id,
+ target: r.target_id,
+ relation: r,
+ })),
+ };
+}
+
+function buildL3(view: C4L3, docsPathSet?: ReadonlySet<string>): BuiltInputs {
+ return {
+ nodes: [
+ ...view.components.map((c) => ({
+ id: c.id,
+ type: "component" as const,
+ data: {
+ kind: "component" as const,
+ component: c,
+ hasDocs: docsPathSet?.has(c.path) ?? false,
+ },
+ })),
+ ...view.external_systems.map((e) => ({
+ id: e.id,
+ type: "external" as const,
+ data: { kind: "external" as const, external: e },
+ })),
+ ],
+ edges: view.relations.map((r, i) => ({
+ id: `e${i}:${r.source_id}->${r.target_id}`,
+ source: r.source_id,
+ target: r.target_id,
+ relation: r,
+ })),
+ };
+}
+
+export interface C4LayoutResult {
+ nodes: Node[];
+ edges: Edge[];
+ loading: boolean;
+}
+
+export interface UseC4LayoutOptions {
+ /** Paths (container.path / component.path) that have a wiki page. */
+ docsPathSet?: ReadonlySet<string>;
+}
+
+export function useC4Layout(
+ level: C4Level,
+ view: C4L1 | C4L2 | C4L3 | null,
+ options: UseC4LayoutOptions = {},
+): C4LayoutResult {
+ const { docsPathSet } = options;
+ const [result, setResult] = useState<C4LayoutResult>({ nodes: [], edges: [], loading: false });
+
+ useEffect(() => {
+ if (!view) {
+ setResult({ nodes: [], edges: [], loading: false });
+ return;
+ }
+ let cancelled = false;
+ setResult((r) => ({ ...r, loading: true }));
+
+ const built =
+ level === 1
+ ? buildL1(view as C4L1)
+ : level === 2
+ ? buildL2(view as C4L2, docsPathSet)
+ : buildL3(view as C4L3, docsPathSet);
+
+ const layoutNodes: C4LayoutNode[] = built.nodes.map((n) => ({
+ id: n.id,
+ width: C4_NODE_SIZES[n.type].width,
+ height: C4_NODE_SIZES[n.type].height,
+ }));
+ const layoutEdges = built.edges.map((e) => ({ id: e.id, source: e.source, target: e.target }));
+
+ void computeC4Layout(layoutNodes, layoutEdges).then((positions) => {
+ if (cancelled) return;
+ const nodes: Node[] = built.nodes.map((n) => {
+ const pos = positions.get(n.id) ?? { x: 0, y: 0, width: 0, height: 0 };
+ return {
+ id: n.id,
+ type: n.type,
+ position: { x: pos.x, y: pos.y },
+ data: n.data as unknown as Record<string, unknown>,
+ width: C4_NODE_SIZES[n.type].width,
+ height: C4_NODE_SIZES[n.type].height,
+ };
+ });
+ const edges: Edge[] = built.edges.map((e) => ({
+ id: e.id,
+ source: e.source,
+ target: e.target,
+ type: "relation",
+ data: { relation: e.relation } as unknown as C4EdgeData & Record<string, unknown>,
+ }));
+ setResult({ nodes, edges, loading: false });
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [level, view, docsPathSet]);
+
+ return result;
+}
diff --git a/packages/ui/src/c4/index.ts b/packages/ui/src/c4/index.ts
new file mode 100644
index 000000000..25e14a21d
--- /dev/null
+++ b/packages/ui/src/c4/index.ts
@@ -0,0 +1,69 @@
+/**
+ * @repowise-dev/ui/c4 — shared C4 diagram surface.
+ *
+ * Public entry point. Host pages compose `<C4Diagram>` with data fetched
+ * from `/api/graph/{repo_id}/c4/{l1,l2,l3}` and either lift state up via
+ * props OR drive it locally with `useC4Store`.
+ */
+
+export { C4Diagram } from "./C4Diagram";
+export type { C4DiagramProps } from "./C4Diagram";
+
+export { useC4Store } from "./store/use-c4-store";
+export type { C4Store, C4StoreState, UseC4StoreOptions } from "./store/use-c4-store";
+
+export { useC4Layout } from "./hooks/use-c4-layout";
+export type { C4LayoutResult } from "./hooks/use-c4-layout";
+export { useC4Keyboard } from "./hooks/use-c4-keyboard";
+
+export { computeC4Layout, C4_NODE_SIZES } from "./layout/elk-c4-layout";
+export type {
+ C4LayoutNode,
+ C4LayoutEdge,
+ C4LayoutPosition,
+} from "./layout/elk-c4-layout";
+
+export { c4NodeTypes } from "./nodes";
+export {
+ SystemNode,
+ PersonNode,
+ ExternalSystemNode,
+ ContainerNode,
+ ComponentNode,
+} from "./nodes";
+
+export { RelationEdge, c4EdgeTypes } from "./edges/RelationEdge";
+
+export {
+ C4ExportMenu,
+ buildC4Svg,
+ downloadSvg,
+ downloadPng,
+ svgToPngBlob,
+} from "./export";
+export type { C4ExportMenuProps, SvgExportOptions, PngExportOptions } from "./export";
+
+export {
+ C4LevelTabs,
+ C4Breadcrumb,
+ C4Legend,
+ C4NodeInspector,
+ C4DetailPanel,
+} from "./panels";
+export type { C4DetailPanelProps, C4Health, C4DocSummary } from "./panels";
+
+export type {
+ C4Level,
+ C4Category,
+ C4Person,
+ C4System,
+ C4ExternalSystem,
+ C4Container,
+ C4Component,
+ C4Relation,
+ C4L1,
+ C4L2,
+ C4L3,
+ C4NodeData,
+ C4EdgeData,
+} from "./types";
diff --git a/packages/ui/src/c4/layout/elk-c4-layout.ts b/packages/ui/src/c4/layout/elk-c4-layout.ts
new file mode 100644
index 000000000..7f5aa2331
--- /dev/null
+++ b/packages/ui/src/c4/layout/elk-c4-layout.ts
@@ -0,0 +1,92 @@
+/**
+ * ELK layout config tailored for C4 diagrams.
+ *
+ * C4 reads top-down: people / system at the top, externals below.
+ * We use the layered algorithm with `DOWN` direction and a generous
+ * inter-layer gap so the labelled relation edges are readable.
+ *
+ * Pure positioning module — no React Flow imports — so the same layout
+ * is reusable for SVG/Mermaid export later.
+ */
+
+import ELK from "elkjs/lib/elk.bundled.js";
+import type { ElkNode, ElkExtendedEdge } from "elkjs";
+
+export interface C4LayoutNode {
+ id: string;
+ width: number;
+ height: number;
+}
+
+export interface C4LayoutEdge {
+ id: string;
+ source: string;
+ target: string;
+}
+
+export interface C4LayoutPosition {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export const C4_NODE_SIZES = {
+ person: { width: 140, height: 90 },
+ system: { width: 220, height: 110 },
+ external: { width: 180, height: 90 },
+ container: { width: 220, height: 110 },
+ component: { width: 180, height: 90 },
+} as const;
+
+const elk = new ELK();
+
+const LAYOUT_OPTIONS: Record<string, string> = {
+ "elk.algorithm": "layered",
+ "elk.direction": "DOWN",
+ "elk.layered.spacing.nodeNodeBetweenLayers": "90",
+ "elk.layered.spacing.edgeNodeBetweenLayers": "40",
+ "elk.spacing.nodeNode": "55",
+ "elk.spacing.componentComponent": "70",
+ "elk.layered.crossingMinimization.strategy": "LAYER_SWEEP",
+ "elk.padding": "[top=30,left=30,bottom=30,right=30]",
+};
+
+export async function computeC4Layout(
+ nodes: C4LayoutNode[],
+ edges: C4LayoutEdge[],
+): Promise<Map<string, C4LayoutPosition>> {
+ if (nodes.length === 0) return new Map();
+
+ const nodeIds = new Set(nodes.map((n) => n.id));
+ const validEdges = edges.filter(
+ (e) => nodeIds.has(e.source) && nodeIds.has(e.target) && e.source !== e.target,
+ );
+
+ const elkGraph: ElkNode = {
+ id: "root",
+ layoutOptions: LAYOUT_OPTIONS,
+ children: nodes.map<ElkNode>((n) => ({
+ id: n.id,
+ width: n.width,
+ height: n.height,
+ })),
+ edges: validEdges.map<ElkExtendedEdge>((e) => ({
+ id: e.id,
+ sources: [e.source],
+ targets: [e.target],
+ })),
+ };
+
+ const laid = await elk.layout(elkGraph);
+ const positions = new Map<string, C4LayoutPosition>();
+ for (const child of laid.children ?? []) {
+ positions.set(child.id, {
+ x: child.x ?? 0,
+ y: child.y ?? 0,
+ width: child.width ?? 0,
+ height: child.height ?? 0,
+ });
+ }
+ return positions;
+}
diff --git a/packages/ui/src/c4/nodes/ComponentNode.tsx b/packages/ui/src/c4/nodes/ComponentNode.tsx
new file mode 100644
index 000000000..fc1cddb2f
--- /dev/null
+++ b/packages/ui/src/c4/nodes/ComponentNode.tsx
@@ -0,0 +1,34 @@
+"use client";
+
+import { memo } from "react";
+import { Files } from "lucide-react";
+import type { NodeProps } from "@xyflow/react";
+import { NodeShell } from "./node-shell";
+import type { C4Component } from "../types";
+
+export interface ComponentNodeProps {
+ component: C4Component;
+ hasDocs?: boolean;
+}
+
+function ComponentNodeImpl(props: NodeProps) {
+ const { data, selected } = props as NodeProps & { data: ComponentNodeProps };
+ const { component, hasDocs } = data;
+ return (
+ <NodeShell
+ tone="component"
+ kindLabel="Component"
+ title={component.name === "_root" ? "(root)" : component.name}
+ subtitle={component.path !== component.name ? component.path : undefined}
+ selected={selected}
+ hasDocs={hasDocs}
+ footer={
+ <span style={{ display: "inline-flex", alignItems: "center", gap: 3 }}>
+ <Files size={11} aria-hidden /> {component.file_count} files · {component.symbol_count} symbols
+ </span>
+ }
+ />
+ );
+}
+
+export const ComponentNode = memo(ComponentNodeImpl);
diff --git a/packages/ui/src/c4/nodes/ContainerNode.tsx b/packages/ui/src/c4/nodes/ContainerNode.tsx
new file mode 100644
index 000000000..1ed073395
--- /dev/null
+++ b/packages/ui/src/c4/nodes/ContainerNode.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { memo, type ReactNode } from "react";
+import { Files, Flame, Skull } from "lucide-react";
+import type { NodeProps } from "@xyflow/react";
+import { NodeShell } from "./node-shell";
+import type { C4Container } from "../types";
+
+export interface ContainerNodeProps {
+ container: C4Container;
+ hasDocs?: boolean;
+}
+
+function ContainerNodeImpl(props: NodeProps) {
+ const { data, selected } = props as NodeProps & { data: ContainerNodeProps };
+ const { container, hasDocs } = data;
+ const chips: ReactNode[] = [
+ <span key="files" style={{ display: "inline-flex", alignItems: "center", gap: 3 }}>
+ <Files size={11} aria-hidden /> {container.file_count}
+ </span>,
+ ];
+ if (container.hotspot_count > 0) {
+ chips.push(
+ <span key="hot" style={{ display: "inline-flex", alignItems: "center", gap: 3, color: "#fca5a5" }}>
+ <Flame size={11} aria-hidden /> {container.hotspot_count}
+ </span>,
+ );
+ }
+ if (container.dead_count > 0) {
+ chips.push(
+ <span key="dead" style={{ display: "inline-flex", alignItems: "center", gap: 3, color: "#cbd5e1" }}>
+ <Skull size={11} aria-hidden /> {container.dead_count}
+ </span>,
+ );
+ }
+ return (
+ <NodeShell
+ tone="container"
+ kindLabel={container.language ? `Container · ${container.language}` : "Container"}
+ title={container.name}
+ subtitle={container.path !== container.name ? container.path : undefined}
+ selected={selected}
+ hasDocs={hasDocs}
+ footer={<div style={{ display: "flex", gap: 10 }}>{chips}</div>}
+ />
+ );
+}
+
+export const ContainerNode = memo(ContainerNodeImpl);
diff --git a/packages/ui/src/c4/nodes/ExternalSystemNode.tsx b/packages/ui/src/c4/nodes/ExternalSystemNode.tsx
new file mode 100644
index 000000000..da8d2a51e
--- /dev/null
+++ b/packages/ui/src/c4/nodes/ExternalSystemNode.tsx
@@ -0,0 +1,47 @@
+"use client";
+
+import { memo } from "react";
+import { Box, Cloud, Wrench, Library } from "lucide-react";
+import type { NodeProps } from "@xyflow/react";
+import { NodeShell } from "./node-shell";
+import type { C4ExternalSystem } from "../types";
+
+export interface ExternalSystemNodeProps {
+ external: C4ExternalSystem;
+}
+
+function categoryIcon(category: string) {
+ switch (category) {
+ case "service":
+ return Cloud;
+ case "tool":
+ return Wrench;
+ case "framework":
+ return Box;
+ default:
+ return Library;
+ }
+}
+
+function ExternalSystemNodeImpl(props: NodeProps) {
+ const { data, selected } = props as NodeProps & { data: ExternalSystemNodeProps };
+ const { external } = data;
+ const Icon = categoryIcon(external.category);
+ const version = external.version ? `v${external.version.replace(/^[\^~]/, "")}` : null;
+ return (
+ <NodeShell
+ tone="external"
+ kindLabel={external.category || "external"}
+ title={external.display_name || external.name}
+ subtitle={external.ecosystem}
+ selected={selected}
+ footer={
+ <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
+ <Icon size={11} aria-hidden /> {version ?? external.name}
+ </span>
+ }
+ />
+ );
+}
+
+export const ExternalSystemNode = memo(ExternalSystemNodeImpl);
diff --git a/packages/ui/src/c4/nodes/PersonNode.tsx b/packages/ui/src/c4/nodes/PersonNode.tsx
new file mode 100644
index 000000000..17774e7a8
--- /dev/null
+++ b/packages/ui/src/c4/nodes/PersonNode.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import { memo } from "react";
+import { User } from "lucide-react";
+import type { NodeProps } from "@xyflow/react";
+import { NodeShell } from "./node-shell";
+import type { C4Person } from "../types";
+
+export interface PersonNodeProps {
+ person: C4Person;
+}
+
+function PersonNodeImpl(props: NodeProps) {
+ const { data, selected } = props as NodeProps & { data: PersonNodeProps };
+ const { person } = data;
+ return (
+ <NodeShell
+ tone="person"
+ kindLabel="Person"
+ title={person.name}
+ subtitle={person.description || undefined}
+ selected={selected}
+ footer={
+ <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
+ <User size={11} aria-hidden /> actor
+ </span>
+ }
+ />
+ );
+}
+
+export const PersonNode = memo(PersonNodeImpl);
diff --git a/packages/ui/src/c4/nodes/SystemNode.tsx b/packages/ui/src/c4/nodes/SystemNode.tsx
new file mode 100644
index 000000000..24399c471
--- /dev/null
+++ b/packages/ui/src/c4/nodes/SystemNode.tsx
@@ -0,0 +1,26 @@
+"use client";
+
+import { memo } from "react";
+import type { NodeProps } from "@xyflow/react";
+import { NodeShell } from "./node-shell";
+import type { C4System } from "../types";
+
+export interface SystemNodeProps {
+ system: C4System;
+}
+
+function SystemNodeImpl(props: NodeProps) {
+ const { data, selected } = props as NodeProps & { data: SystemNodeProps };
+ const { system } = data;
+ return (
+ <NodeShell
+ tone="system"
+ kindLabel="System"
+ title={system.name}
+ subtitle={system.description || "System under analysis"}
+ selected={selected}
+ />
+ );
+}
+
+export const SystemNode = memo(SystemNodeImpl);
diff --git a/packages/ui/src/c4/nodes/index.ts b/packages/ui/src/c4/nodes/index.ts
new file mode 100644
index 000000000..97d32a1af
--- /dev/null
+++ b/packages/ui/src/c4/nodes/index.ts
@@ -0,0 +1,23 @@
+/**
+ * `nodeTypes` map for React Flow + re-exports.
+ *
+ * Node `type` strings map 1:1 to the discriminator in `C4NodeData.kind`,
+ * so layout / builder code can drive React Flow with a single field.
+ */
+
+import type { NodeTypes } from "@xyflow/react";
+import { SystemNode } from "./SystemNode";
+import { PersonNode } from "./PersonNode";
+import { ExternalSystemNode } from "./ExternalSystemNode";
+import { ContainerNode } from "./ContainerNode";
+import { ComponentNode } from "./ComponentNode";
+
+export const c4NodeTypes: NodeTypes = {
+ system: SystemNode,
+ person: PersonNode,
+ external: ExternalSystemNode,
+ container: ContainerNode,
+ component: ComponentNode,
+};
+
+export { SystemNode, PersonNode, ExternalSystemNode, ContainerNode, ComponentNode };
diff --git a/packages/ui/src/c4/nodes/node-shell.tsx b/packages/ui/src/c4/nodes/node-shell.tsx
new file mode 100644
index 000000000..c4ff44112
--- /dev/null
+++ b/packages/ui/src/c4/nodes/node-shell.tsx
@@ -0,0 +1,111 @@
+"use client";
+
+/**
+ * Shared visual chrome for every C4 node — a rounded rect with a tinted
+ * header band, a kind label, a title and an optional subtitle/footer slot.
+ *
+ * Keeps each concrete node component (~30 lines) declarative.
+ */
+
+import * as React from "react";
+import { BookOpen } from "lucide-react";
+import { Handle, Position } from "@xyflow/react";
+
+export type NodeTone =
+ | "system"
+ | "person"
+ | "external"
+ | "container"
+ | "component";
+
+const TONE_STYLES: Record<NodeTone, { bg: string; border: string; band: string; text: string }> = {
+ system: { bg: "#1f3a8a", border: "#1e40af", band: "#1e40af", text: "#ffffff" },
+ person: { bg: "#374151", border: "#4b5563", band: "#4b5563", text: "#ffffff" },
+ external: { bg: "#1f2937", border: "#374151", band: "#374151", text: "#e5e7eb" },
+ container: { bg: "#0f3a5f", border: "#1d4ed8", band: "#1d4ed8", text: "#ffffff" },
+ component: { bg: "#0d2a47", border: "#1e3a8a", band: "#1e3a8a", text: "#e5e7eb" },
+};
+
+export interface NodeShellProps {
+ tone: NodeTone;
+ kindLabel: string;
+ title: string;
+ subtitle?: string | undefined;
+ footer?: React.ReactNode | undefined;
+ selected?: boolean | undefined;
+ width?: number | undefined;
+ height?: number | undefined;
+ hasDocs?: boolean | undefined;
+}
+
+export function NodeShell({
+ tone,
+ kindLabel,
+ title,
+ subtitle,
+ footer,
+ selected,
+ width,
+ height,
+ hasDocs,
+}: NodeShellProps) {
+ const s = TONE_STYLES[tone];
+ return (
+ <div
+ data-c4-tone={tone}
+ style={{
+ width,
+ height,
+ background: s.bg,
+ border: `1.5px solid ${selected ? "#fbbf24" : s.border}`,
+ borderRadius: 8,
+ color: s.text,
+ overflow: "hidden",
+ boxShadow: selected ? "0 0 0 2px rgba(251,191,36,0.4)" : "0 1px 2px rgba(0,0,0,0.2)",
+ fontFamily: "var(--font-sans, system-ui, sans-serif)",
+ display: "flex",
+ flexDirection: "column",
+ }}
+ >
+ <Handle type="target" position={Position.Top} style={{ opacity: 0 }} />
+ <div
+ style={{
+ background: s.band,
+ padding: "3px 8px",
+ fontSize: 9,
+ fontWeight: 600,
+ letterSpacing: 0.6,
+ textTransform: "uppercase",
+ opacity: 0.85,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ gap: 6,
+ }}
+ >
+ <span>{kindLabel}</span>
+ {hasDocs && (
+ <span
+ title="Documentation available"
+ aria-label="Documentation available"
+ style={{ display: "inline-flex", alignItems: "center", opacity: 0.95 }}
+ >
+ <BookOpen size={10} aria-hidden />
+ </span>
+ )}
+ </div>
+ <div style={{ padding: "8px 10px", flex: 1, display: "flex", flexDirection: "column", gap: 2 }}>
+ <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.25, wordBreak: "break-word" }}>
+ {title}
+ </div>
+ {subtitle && (
+ <div style={{ fontSize: 11, opacity: 0.75, lineHeight: 1.3, wordBreak: "break-word" }}>
+ {subtitle}
+ </div>
+ )}
+ {footer && <div style={{ marginTop: "auto", paddingTop: 4, fontSize: 10, opacity: 0.8 }}>{footer}</div>}
+ </div>
+ <Handle type="source" position={Position.Bottom} style={{ opacity: 0 }} />
+ </div>
+ );
+}
diff --git a/packages/ui/src/c4/panels/C4Breadcrumb.tsx b/packages/ui/src/c4/panels/C4Breadcrumb.tsx
new file mode 100644
index 000000000..e925d7b67
--- /dev/null
+++ b/packages/ui/src/c4/panels/C4Breadcrumb.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+import { ChevronRight } from "lucide-react";
+import type { C4Level } from "../types";
+
+export interface C4BreadcrumbProps {
+ level: C4Level;
+ systemName: string;
+ activeContainerPath: string | null;
+ onNavigate: (level: C4Level) => void;
+}
+
+export function C4Breadcrumb({
+ level,
+ systemName,
+ activeContainerPath,
+ onNavigate,
+}: C4BreadcrumbProps) {
+ const segments: { label: string; onClick: () => void; current: boolean }[] = [
+ { label: systemName, onClick: () => onNavigate(1), current: level === 1 },
+ ];
+ if (level >= 2) {
+ segments.push({ label: "Containers", onClick: () => onNavigate(2), current: level === 2 });
+ }
+ if (level === 3 && activeContainerPath) {
+ segments.push({ label: activeContainerPath, onClick: () => onNavigate(3), current: true });
+ }
+ return (
+ <nav
+ aria-label="C4 drill-down breadcrumb"
+ style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 12 }}
+ >
+ {segments.map((seg, i) => (
+ <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
+ {i > 0 && (
+ <ChevronRight size={12} aria-hidden style={{ opacity: 0.5 }} />
+ )}
+ <button
+ type="button"
+ onClick={seg.onClick}
+ disabled={seg.current}
+ style={{
+ background: "none",
+ border: "none",
+ padding: 0,
+ cursor: seg.current ? "default" : "pointer",
+ color: seg.current
+ ? "var(--color-text-primary, #f1f5f9)"
+ : "var(--color-text-secondary, #94a3b8)",
+ fontWeight: seg.current ? 600 : 500,
+ }}
+ >
+ {seg.label}
+ </button>
+ </span>
+ ))}
+ </nav>
+ );
+}
diff --git a/packages/ui/src/c4/panels/C4DetailPanel.tsx b/packages/ui/src/c4/panels/C4DetailPanel.tsx
new file mode 100644
index 000000000..9fba5c34c
--- /dev/null
+++ b/packages/ui/src/c4/panels/C4DetailPanel.tsx
@@ -0,0 +1,349 @@
+"use client";
+
+/**
+ * Rich right-rail for the C4 view.
+ *
+ * Beyond the basic facts shown by C4NodeInspector, this panel optionally
+ * surfaces "context-relevant" data the host has fetched:
+ *
+ * - a documentation excerpt (wiki page) for the selected container/component
+ * - top contributors + recent activity (git ownership)
+ * - module health signals (hotspots, dead, doc coverage)
+ *
+ * The panel is intentionally lazy: every section is shown only if its data
+ * is provided. The host (web page) wires the fetches; the UI package stays
+ * dumb so the same panel works in the hosted frontend.
+ */
+
+import { ExternalLink, X } from "lucide-react";
+import type { ReactNode } from "react";
+import type { C4NodeData } from "../types";
+
+export interface C4Health {
+ health_score: number;
+ hotspot_count: number;
+ dead_code_count: number;
+ doc_coverage_pct: number;
+ primary_owner: string | null;
+ primary_owner_pct: number;
+ contributor_count?: number;
+ is_silo?: boolean;
+}
+
+export interface C4DocSummary {
+ title: string;
+ excerpt: string;
+ /** Optional href the host knows how to open (e.g. /repos/{id}/docs/[page]) */
+ href?: string;
+}
+
+export interface C4DetailPanelProps {
+ data: C4NodeData | null;
+ loading?: boolean;
+
+ doc?: C4DocSummary | null;
+ health?: C4Health | null;
+ contributors?: { name: string; files: number; pct?: number }[];
+
+ /** Render rich docs (markdown) inline instead of the excerpt. Optional. */
+ renderDoc?: (content: string) => ReactNode;
+ docContent?: string | null;
+
+ onClose: () => void;
+ onDrillIn?: ((containerId: string) => void) | undefined;
+ onOpenInGraph?: ((path: string) => void) | undefined;
+ onOpenDoc?: ((href: string) => void) | undefined;
+}
+
+export function C4DetailPanel(props: C4DetailPanelProps) {
+ const { data, onClose } = props;
+ if (!data) return null;
+ return (
+ <aside
+ aria-label="Selected node details"
+ style={{
+ position: "absolute",
+ top: 12,
+ right: 12,
+ width: 360,
+ maxHeight: "calc(100% - 24px)",
+ overflow: "auto",
+ padding: 0,
+ background: "var(--color-bg-elevated, rgba(17,24,39,0.96))",
+ border: "1px solid var(--color-border-default, #334155)",
+ borderRadius: 8,
+ color: "var(--color-text-primary, #f1f5f9)",
+ fontSize: 12,
+ zIndex: 5,
+ display: "flex",
+ flexDirection: "column",
+ boxShadow: "0 10px 30px rgba(0,0,0,0.35)",
+ }}
+ >
+ <Header data={data} onClose={onClose} />
+ <Body {...props} />
+ </aside>
+ );
+}
+
+function Header({ data, onClose }: { data: C4NodeData; onClose: () => void }) {
+ return (
+ <header
+ style={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ padding: "10px 12px",
+ borderBottom: "1px solid var(--color-border-default, #334155)",
+ }}
+ >
+ <span style={{ textTransform: "uppercase", fontSize: 10, letterSpacing: 0.6, opacity: 0.65, fontWeight: 600 }}>
+ {data.kind}
+ </span>
+ <button
+ type="button"
+ aria-label="Close panel"
+ onClick={onClose}
+ style={{ background: "none", border: "none", cursor: "pointer", color: "inherit", padding: 2 }}
+ >
+ <X size={14} />
+ </button>
+ </header>
+ );
+}
+
+function Body(props: C4DetailPanelProps) {
+ const { data } = props;
+ switch (data!.kind) {
+ case "system":
+ return (
+ <Section>
+ <Title>{data!.system.name}</Title>
+ <Sub>{data!.system.description || "System under analysis"}</Sub>
+ </Section>
+ );
+ case "person":
+ return (
+ <Section>
+ <Title>{data!.person.name}</Title>
+ {data!.person.description && <Sub>{data!.person.description}</Sub>}
+ </Section>
+ );
+ case "external": {
+ const e = data!.external;
+ return (
+ <Section>
+ <Title>{e.display_name || e.name}</Title>
+ <Sub>{e.ecosystem} · {e.category}</Sub>
+ <KVList rows={[
+ ["package", e.name],
+ ...(e.version ? [["version", e.version] as [string, string]] : []),
+ ]} />
+ </Section>
+ );
+ }
+ case "container":
+ case "component":
+ return <ContainerOrComponentBody {...props} />;
+ }
+}
+
+function ContainerOrComponentBody(props: C4DetailPanelProps) {
+ const { data, loading, doc, health, contributors, docContent, renderDoc, onDrillIn, onOpenDoc, onOpenInGraph } = props;
+ if (data!.kind !== "container" && data!.kind !== "component") return null;
+ const isContainer = data!.kind === "container";
+ const node = isContainer ? data!.container : data!.component;
+ const path = node.path;
+ return (
+ <>
+ <Section>
+ <Title>{node.name === "_root" ? "(root)" : node.name}</Title>
+ <Sub style={{ fontFamily: "var(--font-mono, ui-monospace, monospace)" }}>{path}</Sub>
+ <ActionRow>
+ {isContainer && onDrillIn && data!.kind === "container" && (
+ <ActionButton onClick={() => onDrillIn(data!.container.id)}>
+ Drill into components →
+ </ActionButton>
+ )}
+ {onOpenInGraph && (
+ <ActionButton onClick={() => onOpenInGraph(path)} variant="ghost">
+ Open in dependency graph
+ </ActionButton>
+ )}
+ </ActionRow>
+ </Section>
+
+ {loading && (
+ <Section>
+ <Sub>Loading details…</Sub>
+ </Section>
+ )}
+
+ {health && (
+ <Section title="Health">
+ <KVList rows={[
+ ["files", String(node.file_count)],
+ ["symbols", String(node.symbol_count)],
+ ["doc coverage", `${Math.round(health.doc_coverage_pct * 100)}%`],
+ ...(health.hotspot_count > 0 ? [["hotspots", String(health.hotspot_count)] as [string, string]] : []),
+ ...(health.dead_code_count > 0 ? [["dead code", String(health.dead_code_count)] as [string, string]] : []),
+ ]} />
+ {health.primary_owner && (
+ <Sub style={{ marginTop: 6 }}>
+ Primary owner: <strong>{health.primary_owner}</strong>{" "}
+ ({Math.round(health.primary_owner_pct * 100)}%)
+ {health.is_silo && (
+ <span style={{ marginLeft: 6, color: "#fbbf24" }}>· silo</span>
+ )}
+ </Sub>
+ )}
+ </Section>
+ )}
+
+ {contributors && contributors.length > 0 && (
+ <Section title="Top contributors">
+ <ul style={{ listStyle: "none", margin: 0, padding: 0 }}>
+ {contributors.slice(0, 5).map((c) => (
+ <li
+ key={c.name}
+ style={{
+ display: "flex",
+ justifyContent: "space-between",
+ padding: "3px 0",
+ borderTop: "1px solid rgba(148,163,184,0.12)",
+ fontSize: 11,
+ }}
+ >
+ <span style={{ opacity: 0.9 }}>{c.name}</span>
+ <span style={{ opacity: 0.6 }}>
+ {c.files} files
+ {c.pct != null && ` · ${Math.round(c.pct * 100)}%`}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </Section>
+ )}
+
+ {doc ? (
+ <Section title="Documentation">
+ <Title style={{ fontSize: 12 }}>{doc.title}</Title>
+ {docContent && renderDoc ? (
+ <div style={{ marginTop: 6, fontSize: 12, lineHeight: 1.45, color: "var(--color-text-secondary, #cbd5e1)" }}>
+ {renderDoc(docContent)}
+ </div>
+ ) : (
+ <Sub style={{ marginTop: 6, whiteSpace: "pre-wrap" }}>{doc.excerpt}</Sub>
+ )}
+ {doc.href && onOpenDoc && (
+ <ActionButton onClick={() => onOpenDoc(doc.href!)} variant="ghost" icon={ExternalLink}>
+ Open full page
+ </ActionButton>
+ )}
+ </Section>
+ ) : (
+ !loading && (
+ <Section title="Documentation">
+ <Sub style={{ opacity: 0.6 }}>No wiki page generated for this path yet.</Sub>
+ </Section>
+ )
+ )}
+ </>
+ );
+}
+
+// --- tiny presentational atoms (keep panel body declarative) ---
+
+function Section({ title, children }: { title?: string; children: ReactNode }) {
+ return (
+ <div style={{ padding: "10px 12px", borderBottom: "1px solid rgba(148,163,184,0.12)" }}>
+ {title && (
+ <div
+ style={{
+ textTransform: "uppercase",
+ fontSize: 10,
+ letterSpacing: 0.6,
+ opacity: 0.55,
+ fontWeight: 600,
+ marginBottom: 6,
+ }}
+ >
+ {title}
+ </div>
+ )}
+ {children}
+ </div>
+ );
+}
+
+function Title({ children, style }: { children: ReactNode; style?: React.CSSProperties }) {
+ return <div style={{ fontWeight: 600, fontSize: 13, ...style }}>{children}</div>;
+}
+
+function Sub({ children, style }: { children: ReactNode; style?: React.CSSProperties }) {
+ return <div style={{ opacity: 0.75, fontSize: 11, lineHeight: 1.4, ...style }}>{children}</div>;
+}
+
+function KVList({ rows }: { rows: [string, string][] }) {
+ return (
+ <div style={{ marginTop: 6 }}>
+ {rows.map(([k, v]) => (
+ <div
+ key={k}
+ style={{
+ display: "flex",
+ justifyContent: "space-between",
+ padding: "3px 0",
+ borderTop: "1px solid rgba(148,163,184,0.12)",
+ fontSize: 11,
+ }}
+ >
+ <span style={{ opacity: 0.6 }}>{k}</span>
+ <span style={{ fontFamily: "var(--font-mono, ui-monospace, monospace)" }}>{v}</span>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function ActionRow({ children }: { children: ReactNode }) {
+ return <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 10 }}>{children}</div>;
+}
+
+function ActionButton({
+ children,
+ onClick,
+ variant = "primary",
+ icon: Icon,
+}: {
+ children: ReactNode;
+ onClick: () => void;
+ variant?: "primary" | "ghost";
+ icon?: React.ComponentType<{ size?: number }>;
+}) {
+ const primary = variant === "primary";
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ style={{
+ padding: "5px 10px",
+ background: primary ? "var(--color-accent-muted, rgba(245,149,32,0.2))" : "transparent",
+ color: primary
+ ? "var(--color-accent-primary, #f59520)"
+ : "var(--color-text-secondary, #cbd5e1)",
+ border: `1px solid ${primary ? "var(--color-accent-primary, #f59520)" : "var(--color-border-default, #334155)"}`,
+ borderRadius: 4,
+ cursor: "pointer",
+ fontSize: 11,
+ fontWeight: 500,
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 5,
+ }}
+ >
+ {Icon && <Icon size={11} />}
+ {children}
+ </button>
+ );
+}
diff --git a/packages/ui/src/c4/panels/C4Legend.tsx b/packages/ui/src/c4/panels/C4Legend.tsx
new file mode 100644
index 000000000..2c90c930b
--- /dev/null
+++ b/packages/ui/src/c4/panels/C4Legend.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+const ITEMS: { label: string; color: string }[] = [
+ { label: "System", color: "#1f3a8a" },
+ { label: "Person", color: "#374151" },
+ { label: "Container", color: "#0f3a5f" },
+ { label: "Component", color: "#0d2a47" },
+ { label: "External", color: "#1f2937" },
+];
+
+export function C4Legend() {
+ return (
+ <div
+ style={{
+ display: "flex",
+ flexWrap: "wrap",
+ gap: 10,
+ padding: "6px 10px",
+ fontSize: 11,
+ color: "var(--color-text-secondary, #94a3b8)",
+ background: "var(--color-bg-surface, rgba(15,23,42,0.7))",
+ border: "1px solid var(--color-border-default, #334155)",
+ borderRadius: 6,
+ }}
+ >
+ {ITEMS.map((it) => (
+ <span key={it.label} style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
+ <span
+ aria-hidden
+ style={{
+ width: 10,
+ height: 10,
+ borderRadius: 2,
+ background: it.color,
+ border: "1px solid rgba(148,163,184,0.4)",
+ }}
+ />
+ {it.label}
+ </span>
+ ))}
+ </div>
+ );
+}
diff --git a/packages/ui/src/c4/panels/C4LevelTabs.tsx b/packages/ui/src/c4/panels/C4LevelTabs.tsx
new file mode 100644
index 000000000..dc444b07f
--- /dev/null
+++ b/packages/ui/src/c4/panels/C4LevelTabs.tsx
@@ -0,0 +1,60 @@
+"use client";
+
+import type { C4Level } from "../types";
+
+interface TabDef {
+ level: C4Level;
+ label: string;
+ hint: string;
+}
+
+const TABS: TabDef[] = [
+ { level: 1, label: "L1 · Context", hint: "System + people + external systems" },
+ { level: 2, label: "L2 · Containers", hint: "Packages / deployable units" },
+ { level: 3, label: "L3 · Components", hint: "Sub-modules inside a container" },
+];
+
+export interface C4LevelTabsProps {
+ level: C4Level;
+ onLevelChange: (level: C4Level) => void;
+ l3Enabled: boolean;
+}
+
+export function C4LevelTabs({ level, onLevelChange, l3Enabled }: C4LevelTabsProps) {
+ return (
+ <div role="tablist" aria-label="C4 level" style={{ display: "flex", gap: 4 }}>
+ {TABS.map((t) => {
+ const disabled = t.level === 3 && !l3Enabled;
+ const active = level === t.level;
+ return (
+ <button
+ key={t.level}
+ type="button"
+ role="tab"
+ aria-selected={active}
+ disabled={disabled}
+ onClick={() => onLevelChange(t.level)}
+ title={disabled ? "Pick a container at L2 first" : t.hint}
+ style={{
+ padding: "5px 12px",
+ fontSize: 12,
+ fontWeight: 500,
+ borderRadius: 6,
+ border: "1px solid var(--color-border-default, #334155)",
+ background: active
+ ? "var(--color-accent-muted, rgba(245,149,32,0.15))"
+ : "transparent",
+ color: active
+ ? "var(--color-accent-primary, #f59520)"
+ : "var(--color-text-secondary, #94a3b8)",
+ cursor: disabled ? "not-allowed" : "pointer",
+ opacity: disabled ? 0.4 : 1,
+ }}
+ >
+ {t.label}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/packages/ui/src/c4/panels/C4NodeInspector.tsx b/packages/ui/src/c4/panels/C4NodeInspector.tsx
new file mode 100644
index 000000000..140e12b52
--- /dev/null
+++ b/packages/ui/src/c4/panels/C4NodeInspector.tsx
@@ -0,0 +1,143 @@
+"use client";
+
+import { X } from "lucide-react";
+import type { C4NodeData } from "../types";
+
+export interface C4NodeInspectorProps {
+ data: C4NodeData | null;
+ onClose: () => void;
+ onDrillIn?: ((containerId: string) => void) | undefined;
+}
+
+export function C4NodeInspector({ data, onClose, onDrillIn }: C4NodeInspectorProps) {
+ if (!data) return null;
+ return (
+ <aside
+ aria-label="Node details"
+ style={{
+ position: "absolute",
+ top: 12,
+ right: 12,
+ width: 280,
+ maxHeight: "70%",
+ overflow: "auto",
+ padding: 12,
+ background: "var(--color-bg-elevated, rgba(17,24,39,0.95))",
+ border: "1px solid var(--color-border-default, #334155)",
+ borderRadius: 8,
+ color: "var(--color-text-primary, #f1f5f9)",
+ fontSize: 12,
+ zIndex: 5,
+ }}
+ >
+ <header
+ style={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ marginBottom: 8,
+ }}
+ >
+ <strong style={{ textTransform: "uppercase", fontSize: 10, letterSpacing: 0.6, opacity: 0.7 }}>
+ {data.kind}
+ </strong>
+ <button
+ type="button"
+ aria-label="Close inspector"
+ onClick={onClose}
+ style={{ background: "none", border: "none", cursor: "pointer", color: "inherit" }}
+ >
+ <X size={14} />
+ </button>
+ </header>
+ <InspectorBody data={data} onDrillIn={onDrillIn} />
+ </aside>
+ );
+}
+
+function InspectorBody({
+ data,
+ onDrillIn,
+}: {
+ data: C4NodeData;
+ onDrillIn?: ((containerId: string) => void) | undefined;
+}) {
+ switch (data.kind) {
+ case "system":
+ return <Row title={data.system.name} sub={data.system.description} />;
+ case "person":
+ return <Row title={data.person.name} sub={data.person.description} />;
+ case "external": {
+ const e = data.external;
+ return (
+ <>
+ <Row title={e.display_name || e.name} sub={e.ecosystem} />
+ <KV k="category" v={e.category} />
+ {e.version && <KV k="version" v={e.version} />}
+ <KV k="name" v={e.name} />
+ </>
+ );
+ }
+ case "container": {
+ const c = data.container;
+ return (
+ <>
+ <Row title={c.name} sub={c.path} />
+ <KV k="language" v={c.language || "—"} />
+ <KV k="files" v={String(c.file_count)} />
+ <KV k="symbols" v={String(c.symbol_count)} />
+ {c.hotspot_count > 0 && <KV k="hotspots" v={String(c.hotspot_count)} />}
+ {c.dead_count > 0 && <KV k="dead" v={String(c.dead_count)} />}
+ {onDrillIn && (
+ <button
+ type="button"
+ onClick={() => onDrillIn(c.id)}
+ style={{
+ marginTop: 10,
+ padding: "5px 10px",
+ background: "var(--color-accent-muted, rgba(245,149,32,0.2))",
+ color: "var(--color-accent-primary, #f59520)",
+ border: "1px solid var(--color-accent-primary, #f59520)",
+ borderRadius: 4,
+ cursor: "pointer",
+ fontSize: 11,
+ fontWeight: 500,
+ }}
+ >
+ Drill into components →
+ </button>
+ )}
+ </>
+ );
+ }
+ case "component": {
+ const c = data.component;
+ return (
+ <>
+ <Row title={c.name === "_root" ? "(root)" : c.name} sub={c.path} />
+ <KV k="container" v={c.container_id} />
+ <KV k="files" v={String(c.file_count)} />
+ <KV k="symbols" v={String(c.symbol_count)} />
+ </>
+ );
+ }
+ }
+}
+
+function Row({ title, sub }: { title: string; sub?: string }) {
+ return (
+ <div style={{ marginBottom: 8 }}>
+ <div style={{ fontWeight: 600, fontSize: 13 }}>{title}</div>
+ {sub && <div style={{ opacity: 0.7, fontSize: 11, marginTop: 2 }}>{sub}</div>}
+ </div>
+ );
+}
+
+function KV({ k, v }: { k: string; v: string }) {
+ return (
+ <div style={{ display: "flex", justifyContent: "space-between", padding: "3px 0", borderTop: "1px solid rgba(148,163,184,0.15)" }}>
+ <span style={{ opacity: 0.6 }}>{k}</span>
+ <span style={{ fontFamily: "var(--font-mono, ui-monospace, monospace)" }}>{v}</span>
+ </div>
+ );
+}
diff --git a/packages/ui/src/c4/panels/index.ts b/packages/ui/src/c4/panels/index.ts
new file mode 100644
index 000000000..b522489cc
--- /dev/null
+++ b/packages/ui/src/c4/panels/index.ts
@@ -0,0 +1,13 @@
+export { C4LevelTabs } from "./C4LevelTabs";
+export type { C4LevelTabsProps } from "./C4LevelTabs";
+export { C4Breadcrumb } from "./C4Breadcrumb";
+export type { C4BreadcrumbProps } from "./C4Breadcrumb";
+export { C4Legend } from "./C4Legend";
+export { C4NodeInspector } from "./C4NodeInspector";
+export type { C4NodeInspectorProps } from "./C4NodeInspector";
+export { C4DetailPanel } from "./C4DetailPanel";
+export type {
+ C4DetailPanelProps,
+ C4Health,
+ C4DocSummary,
+} from "./C4DetailPanel";
diff --git a/packages/ui/src/c4/store/use-c4-store.ts b/packages/ui/src/c4/store/use-c4-store.ts
new file mode 100644
index 000000000..4c424c408
--- /dev/null
+++ b/packages/ui/src/c4/store/use-c4-store.ts
@@ -0,0 +1,90 @@
+"use client";
+
+/**
+ * Minimal hook-based store for the C4 view.
+ *
+ * State is intentionally tiny — level + active container + selected node id —
+ * so we don't pull in zustand for what amounts to three setters. The host
+ * (web page) usually mirrors these into URL params via nuqs; this hook is the
+ * fallback when used standalone (Storybook, tests, hosted frontend).
+ */
+
+import { useCallback, useState } from "react";
+import type { C4Level } from "../types";
+
+export interface C4StoreState {
+ level: C4Level;
+ activeContainerId: string | null;
+ selectedNodeId: string | null;
+}
+
+export interface C4Store extends C4StoreState {
+ setLevel: (level: C4Level) => void;
+ drillIntoContainer: (containerId: string) => void;
+ drillOut: () => void;
+ selectNode: (nodeId: string | null) => void;
+ reset: () => void;
+}
+
+export interface UseC4StoreOptions {
+ initialLevel?: C4Level;
+ initialContainerId?: string | null;
+ onChange?: (state: C4StoreState) => void;
+}
+
+const DEFAULT_STATE: C4StoreState = {
+ level: 2,
+ activeContainerId: null,
+ selectedNodeId: null,
+};
+
+export function useC4Store(options: UseC4StoreOptions = {}): C4Store {
+ const { initialLevel = 2, initialContainerId = null, onChange } = options;
+
+ const [state, setState] = useState<C4StoreState>({
+ level: initialLevel,
+ activeContainerId: initialContainerId,
+ selectedNodeId: null,
+ });
+
+ const update = useCallback(
+ (next: C4StoreState) => {
+ setState(next);
+ onChange?.(next);
+ },
+ [onChange],
+ );
+
+ const setLevel = useCallback(
+ (level: C4Level) =>
+ update({
+ level,
+ activeContainerId: level === 3 ? state.activeContainerId : null,
+ selectedNodeId: null,
+ }),
+ [state.activeContainerId, update],
+ );
+
+ const drillIntoContainer = useCallback(
+ (containerId: string) =>
+ update({ level: 3, activeContainerId: containerId, selectedNodeId: null }),
+ [update],
+ );
+
+ const drillOut = useCallback(() => {
+ if (state.level === 3) {
+ update({ level: 2, activeContainerId: null, selectedNodeId: null });
+ } else if (state.level === 2) {
+ update({ level: 1, activeContainerId: null, selectedNodeId: null });
+ }
+ }, [state.level, update]);
+
+ const selectNode = useCallback(
+ (nodeId: string | null) => update({ ...state, selectedNodeId: nodeId }),
+ [state, update],
+ );
+
+ const reset = useCallback(() => update(DEFAULT_STATE), [update]);
+
+ return { ...state, setLevel, drillIntoContainer, drillOut, selectNode, reset };
+}
diff --git a/packages/ui/src/c4/types.ts b/packages/ui/src/c4/types.ts
new file mode 100644
index 000000000..59654eb57
--- /dev/null
+++ b/packages/ui/src/c4/types.ts
@@ -0,0 +1,90 @@
+/**
+ * Frontend mirror of the backend C4 Pydantic models from
+ * `packages/server/src/repowise/server/schemas.py`. Keep field names in
+ * lock-step — these are the on-the-wire shapes returned by /api/graph/{id}/c4/*.
+ */
+
+export type C4Level = 1 | 2 | 3;
+
+export type C4Category = "framework" | "service" | "tool" | "library";
+
+export interface C4Person {
+ id: string;
+ name: string;
+ description: string;
+}
+
+export interface C4System {
+ id: string;
+ name: string;
+ description: string;
+}
+
+export interface C4ExternalSystem {
+ id: string;
+ name: string;
+ display_name: string;
+ category: C4Category | string;
+ ecosystem: string;
+ version: string | null;
+}
+
+export interface C4Container {
+ id: string;
+ name: string;
+ path: string;
+ language: string;
+ file_count: number;
+ symbol_count: number;
+ hotspot_count: number;
+ dead_count: number;
+}
+
+export interface C4Component {
+ id: string;
+ name: string;
+ path: string;
+ container_id: string;
+ file_count: number;
+ symbol_count: number;
+}
+
+export interface C4Relation {
+ source_id: string;
+ target_id: string;
+ label: string;
+ edge_count: number;
+ edge_types: string[];
+}
+
+export interface C4L1 {
+ system: C4System;
+ people: C4Person[];
+ external_systems: C4ExternalSystem[];
+ relations: C4Relation[];
+}
+
+export interface C4L2 {
+ containers: C4Container[];
+ external_systems: C4ExternalSystem[];
+ relations: C4Relation[];
+}
+
+export interface C4L3 {
+ container: C4Container;
+ components: C4Component[];
+ external_systems: C4ExternalSystem[];
+ relations: C4Relation[];
+}
+
+/** Node `data` payloads attached to React Flow nodes. Discriminated by `kind`. */
+export type C4NodeData =
+ | { kind: "system"; system: C4System }
+ | { kind: "person"; person: C4Person }
+ | { kind: "external"; external: C4ExternalSystem }
+ | { kind: "container"; container: C4Container }
+ | { kind: "component"; component: C4Component };
+
+export interface C4EdgeData {
+ relation: C4Relation;
+}
diff --git a/packages/web/src/app/repos/[id]/c4/loading.tsx b/packages/web/src/app/repos/[id]/c4/loading.tsx
new file mode 100644
index 000000000..84ed7261c
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/c4/loading.tsx
@@ -0,0 +1,15 @@
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+
+export default function Loading() {
+ return (
+ <div className="flex flex-col h-full">
+ <div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]">
+ <Skeleton className="h-5 w-40" />
+ <Skeleton className="mt-2 h-3 w-72" />
+ </div>
+ <div className="flex-1 p-6">
+ <Skeleton className="h-full w-full rounded-lg" />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/c4/page.tsx b/packages/web/src/app/repos/[id]/c4/page.tsx
new file mode 100644
index 000000000..3038bdfc4
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/c4/page.tsx
@@ -0,0 +1,122 @@
+"use client";
+
+/**
+ * C4 architecture diagrams — `/repos/[id]/c4`.
+ *
+ * Thin wrapper around `<C4Diagram>` from @repowise-dev/ui/c4. State (level +
+ * active container) is mirrored into URL params via nuqs so refresh + share
+ * preserve the view.
+ */
+
+import { use, useCallback } from "react";
+import { useQueryState, parseAsInteger, parseAsString } from "nuqs";
+import { C4Diagram, type C4Level } from "@repowise-dev/ui/c4";
+import { useC4L1, useC4L2, useC4L3 } from "@/lib/hooks/use-c4";
+import { useC4DocsPathSet } from "@/lib/hooks/use-c4-context";
+import { useRepo } from "@/lib/hooks/use-repo";
+import { getC4Mermaid } from "@/lib/api/c4";
+import { C4DetailPanelHost } from "@/components/c4/c4-detail-panel-host";
+
+function clampLevel(n: number | null): C4Level {
+ return n === 1 ? 1 : n === 3 ? 3 : 2;
+}
+
+export default function C4Page({ params }: { params: Promise<{ id: string }> }) {
+ const { id: repoId } = use(params);
+ const { repo } = useRepo(repoId);
+
+ const [levelParam, setLevelParam] = useQueryState(
+ "level",
+ parseAsInteger.withDefault(2),
+ );
+ const [containerParam, setContainerParam] = useQueryState(
+ "container",
+ parseAsString,
+ );
+
+ const level = clampLevel(levelParam);
+ const activeContainerId = containerParam || null;
+
+ const { view: l1View, error: l1Err, isLoading: l1Loading } = useC4L1(level === 1 ? repoId : null);
+ const { view: l2View, error: l2Err, isLoading: l2Loading } = useC4L2(level >= 2 ? repoId : null);
+ const { view: l3View, error: l3Err, isLoading: l3Loading } = useC4L3(
+ level === 3 ? repoId : null,
+ level === 3 ? activeContainerId : null,
+ );
+
+ const setLevel = useCallback(
+ (next: C4Level) => {
+ void setLevelParam(next);
+ if (next !== 3) void setContainerParam(null);
+ },
+ [setContainerParam, setLevelParam],
+ );
+
+ const drillInto = useCallback(
+ (containerId: string) => {
+ void setLevelParam(3);
+ void setContainerParam(containerId);
+ },
+ [setContainerParam, setLevelParam],
+ );
+
+ const drillOut = useCallback(() => {
+ if (level === 3) {
+ void setLevelParam(2);
+ void setContainerParam(null);
+ } else if (level === 2) {
+ void setLevelParam(1);
+ }
+ }, [level, setContainerParam, setLevelParam]);
+
+ const loading =
+ level === 1 ? l1Loading : level === 2 ? l2Loading : l3Loading;
+ const error =
+ level === 1 ? l1Err : level === 2 ? l2Err : l3Err;
+
+ const { pathSet: docsPathSet, pageIdByPath } = useC4DocsPathSet(repoId);
+
+ const fetchMermaid = useCallback(
+ () => getC4Mermaid(repoId, level, activeContainerId),
+ [activeContainerId, level, repoId],
+ );
+
+ return (
+ <div className="flex flex-col h-full">
+ <div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]">
+ <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">
+ C4 Architecture
+ </h1>
+ <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">
+ System context, containers, and components — drill in to navigate.
+ </p>
+ </div>
+ <div className="flex-1 min-h-0">
+ <C4Diagram
+ level={level}
+ activeContainerId={activeContainerId}
+ systemName={repo?.name ?? "System"}
+ l1View={l1View}
+ l2View={l2View}
+ l3View={l3View}
+ loading={loading}
+ error={error}
+ onLevelChange={setLevel}
+ onDrillInto={drillInto}
+ onDrillOut={drillOut}
+ docsPathSet={docsPathSet}
+ fetchMermaid={fetchMermaid}
+ renderInspector={({ data, onClose, onDrillIn }) => (
+ <C4DetailPanelHost
+ repoId={repoId}
+ data={data}
+ pageIdByPath={pageIdByPath}
+ onClose={onClose}
+ onDrillIn={onDrillIn}
+ />
+ )}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/c4/c4-detail-panel-host.tsx b/packages/web/src/components/c4/c4-detail-panel-host.tsx
new file mode 100644
index 000000000..eeeed7353
--- /dev/null
+++ b/packages/web/src/components/c4/c4-detail-panel-host.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+/**
+ * Web-side wrapper around <C4DetailPanel> that fetches per-selection
+ * docs + module health and feeds them into the shared UI panel.
+ *
+ * The shared panel lives in @repowise-dev/ui/c4 — no fetch logic. This
+ * host knits SWR data into the panel's prop shape.
+ */
+
+import { useRouter } from "next/navigation";
+import { C4DetailPanel, type C4NodeData } from "@repowise-dev/ui/c4";
+import { ChatMarkdown } from "@repowise-dev/ui/chat/chat-markdown";
+import {
+ useC4SelectionContext,
+} from "@/lib/hooks/use-c4-context";
+
+interface C4DetailPanelHostProps {
+ repoId: string;
+ data: C4NodeData;
+ pageIdByPath: ReadonlyMap<string, string>;
+ onClose: () => void;
+ onDrillIn?: ((containerId: string) => void) | undefined;
+}
+
+function selectionPath(data: C4NodeData): string | null {
+ if (data.kind === "container") return data.container.path;
+ if (data.kind === "component") return data.component.path;
+ return null;
+}
+
+export function C4DetailPanelHost({
+ repoId,
+ data,
+ pageIdByPath,
+ onClose,
+ onDrillIn,
+}: C4DetailPanelHostProps) {
+ const router = useRouter();
+ const path = selectionPath(data);
+ const pageId = path ? pageIdByPath.get(path) ?? null : null;
+
+ const { health, page, isLoading } = useC4SelectionContext(repoId, path, pageId);
+
+ const doc = page
+ ? {
+ title: page.title,
+ excerpt: page.content.split("\n").slice(0, 6).join("\n"),
+ href: `/repos/${repoId}/docs/${encodeURIComponent(page.id)}`,
+ }
+ : null;
+
+ const contributors =
+ health?.owners?.slice(0, 5).map((o) => ({ name: o.name, files: o.file_count, pct: o.pct })) ?? [];
+
+ return (
+ <C4DetailPanel
+ data={data}
+ loading={isLoading}
+ doc={doc}
+ docContent={page?.content ?? null}
+ renderDoc={(content) => <ChatMarkdown content={content} />}
+ health={
+ health
+ ? {
+ health_score: health.health_score,
+ hotspot_count: health.hotspot_count,
+ dead_code_count: health.dead_code_count,
+ doc_coverage_pct: health.doc_coverage_pct,
+ primary_owner: health.primary_owner,
+ primary_owner_pct: health.primary_owner_pct,
+ contributor_count: health.contributor_count,
+ is_silo: health.is_silo,
+ }
+ : null
+ }
+ contributors={contributors}
+ onClose={onClose}
+ onDrillIn={onDrillIn}
+ onOpenInGraph={path ? (p) => router.push(`/repos/${repoId}/graph?node=${encodeURIComponent(p)}`) : undefined}
+ onOpenDoc={(href) => router.push(href)}
+ />
+ );
+}
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index acbda7a6f..f750eddc0 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -23,6 +23,7 @@ import {
Link2,
GitMerge,
Users,
+ Boxes,
} from "lucide-react";
import { cn } from "@/lib/utils/cn";
import { ScrollArea } from "@repowise-dev/ui/ui/scroll-area";
@@ -56,6 +57,7 @@ function repoNavItems(repoId: string): NavItem[] {
{ label: "Chat", href: `/repos/${repoId}`, icon: MessageSquare, exact: true },
{ label: "Risk", href: `/repos/${repoId}/risk`, icon: ShieldAlert },
{ label: "Graph", href: `/repos/${repoId}/graph`, icon: GitBranch },
+ { label: "C4 Diagram", href: `/repos/${repoId}/c4`, icon: Boxes },
{ label: "Symbols", href: `/repos/${repoId}/symbols`, icon: Code2 },
{ label: "Contributors", href: `/repos/${repoId}/owners`, icon: Users },
{ label: "Decisions", href: `/repos/${repoId}/decisions`, icon: Lightbulb },
diff --git a/packages/web/src/lib/api/c4.ts b/packages/web/src/lib/api/c4.ts
new file mode 100644
index 000000000..89949916f
--- /dev/null
+++ b/packages/web/src/lib/api/c4.ts
@@ -0,0 +1,47 @@
+/**
+ * REST client for the C4 endpoints.
+ * Backend: packages/server/src/repowise/server/routers/c4.py
+ */
+
+import { apiGet } from "./client";
+import type { C4L1, C4L2, C4L3 } from "@repowise-dev/ui/c4";
+
+export async function getC4L1(repoId: string): Promise<C4L1> {
+ return apiGet<C4L1>(`/api/graph/${repoId}/c4/l1`);
+}
+
+export async function getC4L2(repoId: string): Promise<C4L2> {
+ return apiGet<C4L2>(`/api/graph/${repoId}/c4/l2`);
+}
+
+export async function getC4L3(repoId: string, containerId: string): Promise<C4L3> {
+ return apiGet<C4L3>(`/api/graph/${repoId}/c4/l3`, { container_id: containerId });
+}
+
+/**
+ * Fetch the Mermaid C4 source for the current view. Backend is the source
+ * of truth so the exported diagram matches what the API serves.
+ */
+export async function getC4Mermaid(
+ repoId: string,
+ level: 1 | 2 | 3,
+ containerId?: string | null,
+): Promise<string> {
+ const params = new URLSearchParams({ level: String(level) });
+ if (level === 3 && containerId) params.set("container_id", containerId);
+ const apiBase =
+ typeof window !== "undefined"
+ ? (process.env.NEXT_PUBLIC_REPOWISE_API_URL ?? "")
+ : "";
+ const apiKey =
+ typeof window !== "undefined"
+ ? localStorage.getItem("repowise_api_key")
+ : null;
+ const res = await fetch(`${apiBase}/api/graph/${repoId}/c4/mermaid?${params.toString()}`, {
+ headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {},
+ });
+ if (!res.ok) {
+ throw new Error(`Failed to fetch Mermaid C4 source (${res.status})`);
+ }
+ return res.text();
+}
diff --git a/packages/web/src/lib/hooks/use-c4-context.ts b/packages/web/src/lib/hooks/use-c4-context.ts
new file mode 100644
index 000000000..5af956d54
--- /dev/null
+++ b/packages/web/src/lib/hooks/use-c4-context.ts
@@ -0,0 +1,87 @@
+"use client";
+
+/**
+ * Side-data hooks for the C4 inspector.
+ *
+ * - useC4DocsPathSet: one fetch per repo → Set of paths that already have a
+ * generated wiki page. Used to render the "has docs" badge on container /
+ * component nodes without N+1 round-trips.
+ *
+ * - useC4SelectionContext: per-selection fetch → module health + page body
+ * for the active container/component path. Skipped for system / person /
+ * external selections.
+ */
+
+import { useMemo } from "react";
+import useSWR from "swr";
+import { listAllPages, getPageById } from "@/lib/api/pages";
+import { getModuleHealth } from "@/lib/api/modules";
+import type { ModuleHealthDetail, PageResponse } from "@/lib/api/types";
+
+const SWR_OPTS = { revalidateOnFocus: false, revalidateOnReconnect: false };
+
+const DOC_PAGE_TYPES = new Set(["module_page", "file_page"]);
+
+interface DocsIndex {
+ pathSet: ReadonlySet<string>;
+ pageIdByPath: ReadonlyMap<string, string>;
+}
+
+const EMPTY_DOCS_INDEX: DocsIndex = {
+ pathSet: new Set(),
+ pageIdByPath: new Map(),
+};
+
+export function useC4DocsPathSet(repoId: string | null): DocsIndex {
+ const { data } = useSWR<PageResponse[]>(
+ repoId ? `c4-docs-index:${repoId}` : null,
+ () => listAllPages(repoId!),
+ SWR_OPTS,
+ );
+ return useMemo(() => {
+ if (!data) return EMPTY_DOCS_INDEX;
+ const pathSet = new Set<string>();
+ const pageIdByPath = new Map<string, string>();
+ for (const p of data) {
+ if (!DOC_PAGE_TYPES.has(p.page_type)) continue;
+ if (!p.target_path) continue;
+ pathSet.add(p.target_path);
+ // Prefer module_page over file_page when both exist for the same path.
+ const existingId = pageIdByPath.get(p.target_path);
+ if (!existingId || p.page_type === "module_page") {
+ pageIdByPath.set(p.target_path, p.id);
+ }
+ }
+ return { pathSet, pageIdByPath };
+ }, [data]);
+}
+
+export interface C4SelectionContext {
+ health: ModuleHealthDetail | null;
+ page: PageResponse | null;
+ isLoading: boolean;
+}
+
+export function useC4SelectionContext(
+ repoId: string | null,
+ path: string | null,
+ pageId: string | null,
+): C4SelectionContext {
+ const { data: health, isLoading: healthLoading } = useSWR<ModuleHealthDetail>(
+ repoId && path ? `c4-health:${repoId}:${path}` : null,
+ () => getModuleHealth(repoId!, path!),
+ SWR_OPTS,
+ );
+
+ const { data: page, isLoading: pageLoading } = useSWR<PageResponse>(
+ pageId ? `c4-page:${pageId}` : null,
+ () => getPageById(pageId!),
+ SWR_OPTS,
+ );
+
+ return {
+ health: (health as ModuleHealthDetail | undefined) ?? null,
+ page: (page as PageResponse | undefined) ?? null,
+ isLoading: healthLoading || pageLoading,
+ };
+}
diff --git a/packages/web/src/lib/hooks/use-c4.ts b/packages/web/src/lib/hooks/use-c4.ts
new file mode 100644
index 000000000..bd8dfbe3e
--- /dev/null
+++ b/packages/web/src/lib/hooks/use-c4.ts
@@ -0,0 +1,39 @@
+"use client";
+
+/**
+ * SWR-backed hooks for the C4 endpoints. One hook per level so consumers
+ * can opt into only what they render — L1 view doesn't need to fetch L3.
+ */
+
+import useSWR from "swr";
+import type { C4L1, C4L2, C4L3 } from "@repowise-dev/ui/c4";
+import { getC4L1, getC4L2, getC4L3 } from "@/lib/api/c4";
+
+const SWR_OPTS = { revalidateOnFocus: false, revalidateOnReconnect: false };
+
+export function useC4L1(repoId: string | null) {
+ const { data, error, isLoading } = useSWR<C4L1>(
+ repoId ? `c4-l1:${repoId}` : null,
+ () => getC4L1(repoId!),
+ SWR_OPTS,
+ );
+ return { view: data ?? null, error: (error as Error | undefined) ?? null, isLoading };
+}
+
+export function useC4L2(repoId: string | null) {
+ const { data, error, isLoading } = useSWR<C4L2>(
+ repoId ? `c4-l2:${repoId}` : null,
+ () => getC4L2(repoId!),
+ SWR_OPTS,
+ );
+ return { view: data ?? null, error: (error as Error | undefined) ?? null, isLoading };
+}
+
+export function useC4L3(repoId: string | null, containerId: string | null) {
+ const { data, error, isLoading } = useSWR<C4L3>(
+ repoId && containerId ? `c4-l3:${repoId}:${containerId}` : null,
+ () => getC4L3(repoId!, containerId!),
+ SWR_OPTS,
+ );
+ return { view: data ?? null, error: (error as Error | undefined) ?? null, isLoading };
+}
diff --git a/tests/unit/ingestion/external_systems/test_cargo_go_nuget.py b/tests/unit/ingestion/external_systems/test_cargo_go_nuget.py
new file mode 100644
index 000000000..17d586367
--- /dev/null
+++ b/tests/unit/ingestion/external_systems/test_cargo_go_nuget.py
@@ -0,0 +1,107 @@
+"""Tests for cargo, go, and nuget manifest parsers."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion.external_systems import cargo, go, nuget
+
+
+def _write(tmp_path: Path, rel: str, content: str) -> Path:
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(content, encoding="utf-8")
+ return p
+
+
+def test_cargo_parses_sections_and_skips_path_deps(tmp_path):
+ p = _write(
+ tmp_path,
+ "Cargo.toml",
+ """
+[dependencies]
+serde = "1.0"
+tokio = {version = "1.0", features = ["full"]}
+local = {path = "../local"}
+
+[dev-dependencies]
+pretty_assertions = "1.0"
+""",
+ )
+ records = cargo.parse(p, tmp_path)
+ names = {r.name for r in records}
+ assert names == {"serde", "tokio", "pretty_assertions"}
+ by_name = {r.name: r for r in records}
+ assert by_name["tokio"].version == "1.0"
+ assert by_name["pretty_assertions"].is_dev_dep is True
+
+
+def test_go_parses_block_and_drops_local_replacements(tmp_path):
+ p = _write(
+ tmp_path,
+ "go.mod",
+ """
+module github.com/example/app
+
+go 1.22
+
+require (
+ github.com/gin-gonic/gin v1.10.0
+ github.com/google/uuid v1.6.0 // indirect
+)
+
+require github.com/sirupsen/logrus v1.9.3
+
+replace github.com/internal/lib => ../lib
+""",
+ )
+ records = go.parse(p, tmp_path)
+ by_name = {r.name: r for r in records}
+ assert "github.com/gin-gonic/gin" in by_name
+ assert "github.com/sirupsen/logrus" in by_name
+ assert by_name["github.com/google/uuid"].is_dev_dep is True # // indirect → dev
+ assert by_name["github.com/gin-gonic/gin"].version == "v1.10.0"
+
+
+def test_go_drops_local_path_replacements(tmp_path):
+ p = _write(
+ tmp_path,
+ "go.mod",
+ """
+module example
+require github.com/internal/lib v0.1.0
+replace github.com/internal/lib => ./internal/lib
+""",
+ )
+ records = go.parse(p, tmp_path)
+ assert records == []
+
+
+def test_nuget_parses_package_references(tmp_path):
+ p = _write(
+ tmp_path,
+ "App.csproj",
+ """<?xml version="1.0"?>
+<Project Sdk="Microsoft.NET.Sdk">
+ <ItemGroup>
+ <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
+ <PackageReference Include="Serilog">
+ <Version>3.1.1</Version>
+ </PackageReference>
+ <ProjectReference Include="..\\Other\\Other.csproj" />
+ </ItemGroup>
+</Project>
+""",
+ )
+ records = nuget.parse(p, tmp_path)
+ by_name = {r.name: r for r in records}
+ assert set(by_name) == {"Newtonsoft.Json", "Serilog"}
+ assert by_name["Newtonsoft.Json"].version == "13.0.3"
+ assert by_name["Serilog"].version == "3.1.1"
+
+
+def test_malformed_inputs_return_empty(tmp_path):
+ bad_cargo = _write(tmp_path, "Cargo.toml", "this isn't toml [[")
+ assert cargo.parse(bad_cargo, tmp_path) == []
+ bad_xml = _write(tmp_path, "Bad.csproj", "<Project><not closed")
+ assert nuget.parse(bad_xml, tmp_path) == []
diff --git a/tests/unit/ingestion/external_systems/test_classifier.py b/tests/unit/ingestion/external_systems/test_classifier.py
new file mode 100644
index 000000000..7e6678b66
--- /dev/null
+++ b/tests/unit/ingestion/external_systems/test_classifier.py
@@ -0,0 +1,36 @@
+"""Tests for the dependency-name → C4 category classifier."""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.external_systems.classifier import classify, display_name_for
+
+
+def test_framework_names():
+ assert classify("fastapi") == "framework"
+ assert classify("next") == "framework"
+ assert classify("react") == "framework"
+
+
+def test_service_names_and_patterns():
+ assert classify("stripe") == "service"
+ assert classify("@aws-sdk/client-s3") == "service"
+ assert classify("@google-cloud/storage") == "service"
+ assert classify("boto3") == "service"
+
+
+def test_tool_names():
+ assert classify("eslint") == "tool"
+ assert classify("pytest") == "tool"
+
+
+def test_unknown_defaults_to_library():
+ assert classify("some-random-pkg-23") == "library"
+
+
+def test_classifier_is_case_insensitive():
+ assert classify("FastAPI") == "framework"
+
+
+def test_display_name_strips_scope_and_normalises():
+ assert display_name_for("@aws-sdk/client-s3") == "Client S3"
+ assert display_name_for("tree-sitter-python") == "Tree Sitter Python"
diff --git a/tests/unit/ingestion/external_systems/test_npm.py b/tests/unit/ingestion/external_systems/test_npm.py
new file mode 100644
index 000000000..577075ab3
--- /dev/null
+++ b/tests/unit/ingestion/external_systems/test_npm.py
@@ -0,0 +1,78 @@
+"""Tests for the npm package.json parser."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from repowise.core.ingestion.external_systems import npm
+
+
+def _write(tmp_path: Path, rel: str, data: dict) -> Path:
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(json.dumps(data), encoding="utf-8")
+ return p
+
+
+def test_parses_dependencies_and_dev_dependencies(tmp_path):
+ manifest = _write(
+ tmp_path,
+ "package.json",
+ {
+ "dependencies": {"react": "^18.0.0", "@aws-sdk/client-s3": "^3.0.0"},
+ "devDependencies": {"vitest": "^1.0.0"},
+ },
+ )
+ records = npm.parse(manifest, tmp_path)
+ names = {r.name for r in records}
+ assert names == {"react", "@aws-sdk/client-s3", "vitest"}
+
+ react = next(r for r in records if r.name == "react")
+ assert react.version == "^18.0.0"
+ assert react.is_dev_dep is False
+ assert react.category == "framework"
+ assert react.ecosystem == "npm"
+
+ aws = next(r for r in records if r.name == "@aws-sdk/client-s3")
+ assert aws.category == "service"
+
+ vitest = next(r for r in records if r.name == "vitest")
+ assert vitest.is_dev_dep is True
+ assert vitest.category == "tool"
+
+
+def test_handles_malformed_json_without_raising(tmp_path):
+ p = tmp_path / "package.json"
+ p.write_text("{ not valid", encoding="utf-8")
+ assert npm.parse(p, tmp_path) == []
+
+
+def test_skips_workspace_members(tmp_path):
+ # Root manifest declares workspaces + a "dep" that is actually a workspace.
+ _write(
+ tmp_path,
+ "packages/core/package.json",
+ {"name": "@org/core"},
+ )
+ root = _write(
+ tmp_path,
+ "package.json",
+ {
+ "workspaces": ["packages/*"],
+ "dependencies": {"@org/core": "workspace:*", "react": "^18"},
+ },
+ )
+ records = npm.parse(root, tmp_path)
+ names = {r.name for r in records}
+ assert names == {"react"}
+
+
+def test_declared_in_is_repo_relative_posix(tmp_path):
+ nested = _write(
+ tmp_path,
+ "packages/web/package.json",
+ {"dependencies": {"next": "^14"}},
+ )
+ records = npm.parse(nested, tmp_path)
+ assert records[0].declared_in == "packages/web/package.json"
diff --git a/tests/unit/ingestion/external_systems/test_pypi.py b/tests/unit/ingestion/external_systems/test_pypi.py
new file mode 100644
index 000000000..c0d48c84b
--- /dev/null
+++ b/tests/unit/ingestion/external_systems/test_pypi.py
@@ -0,0 +1,84 @@
+"""Tests for the pypi (pyproject / requirements) parser."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion.external_systems import pypi
+
+
+def _write(tmp_path: Path, rel: str, content: str) -> Path:
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(content, encoding="utf-8")
+ return p
+
+
+def test_parses_pep621_dependencies(tmp_path):
+ pyproject = _write(
+ tmp_path,
+ "pyproject.toml",
+ """
+[project]
+name = "demo"
+dependencies = [
+ "fastapi>=0.100",
+ "httpx[http2]>=0.27,<1",
+]
+
+[project.optional-dependencies]
+dev = ["pytest>=7", "ruff>=0.5"]
+""",
+ )
+ records = pypi.parse(pyproject, tmp_path)
+ names = {r.name for r in records}
+ assert {"fastapi", "httpx", "pytest", "ruff"} <= names
+
+ fastapi = next(r for r in records if r.name == "fastapi")
+ assert fastapi.is_dev_dep is False
+ assert fastapi.category == "framework"
+
+ pytest_rec = next(r for r in records if r.name == "pytest")
+ assert pytest_rec.is_dev_dep is True
+ assert pytest_rec.category == "tool"
+
+
+def test_parses_poetry_layout(tmp_path):
+ pyproject = _write(
+ tmp_path,
+ "pyproject.toml",
+ """
+[tool.poetry]
+name = "demo"
+
+[tool.poetry.dependencies]
+python = "^3.11"
+django = "^5.0"
+stripe = {version = "^7.0"}
+
+[tool.poetry.group.dev.dependencies]
+black = "^24"
+""",
+ )
+ records = pypi.parse(pyproject, tmp_path)
+ by_name = {r.name: r for r in records}
+ assert "django" in by_name and by_name["django"].category == "framework"
+ assert "stripe" in by_name and by_name["stripe"].category == "service"
+ assert by_name["black"].is_dev_dep is True
+ assert "python" not in by_name # explicit skip
+
+
+def test_requirements_txt(tmp_path):
+ p = _write(
+ tmp_path,
+ "requirements.txt",
+ "# comment\nfastapi==0.110\nrequests>=2 ; python_version > '3'\n-e .\n",
+ )
+ records = pypi.parse(p, tmp_path)
+ names = {r.name for r in records}
+ assert names == {"fastapi", "requests"}
+
+
+def test_malformed_pyproject_returns_empty(tmp_path):
+ p = _write(tmp_path, "pyproject.toml", "not [ valid toml")
+ assert pypi.parse(p, tmp_path) == []
diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.py
index 5855be483..a486efe50 100644
--- a/tests/unit/persistence/test_models.py
+++ b/tests/unit/persistence/test_models.py
@@ -307,5 +307,6 @@ def test_base_includes_all_models():
"llm_costs",
"security_findings",
"answer_cache",
+ "external_systems",
}
assert expected == table_names
diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.py
index 26451f7bd..0d23bfb71 100644
--- a/tests/unit/server/conftest.py
+++ b/tests/unit/server/conftest.py
@@ -28,6 +28,7 @@ def _create_test_app():
from fastapi import FastAPI
from repowise.server.routers import (
+ c4,
dead_code,
decisions,
git,
@@ -70,6 +71,7 @@ def _create_test_app():
app.include_router(jobs.router)
app.include_router(symbols.router)
app.include_router(graph.router)
+ app.include_router(c4.router)
app.include_router(webhooks.router)
app.include_router(git.router)
app.include_router(dead_code.router)
diff --git a/tests/unit/server/services/conftest.py b/tests/unit/server/services/conftest.py
new file mode 100644
index 000000000..3d7158f75
--- /dev/null
+++ b/tests/unit/server/services/conftest.py
@@ -0,0 +1,32 @@
+"""Fixtures for server service tests.
+
+Re-uses the in-memory SQLite engine pattern from the persistence tests but
+defined locally so this file doesn't depend on tests/unit/persistence.
+"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+
+from repowise.core.persistence.database import init_db
+
+
+async def async_engine():
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(engine)
+ yield engine
+ await engine.dispose()
+
+
+async def async_session(async_engine):
+ factory = async_sessionmaker(async_engine, expire_on_commit=False, class_=AsyncSession)
+ async with factory() as session:
+ yield session
diff --git a/tests/unit/server/services/test_c4_builder.py b/tests/unit/server/services/test_c4_builder.py
new file mode 100644
index 000000000..23567265f
--- /dev/null
+++ b/tests/unit/server/services/test_c4_builder.py
@@ -0,0 +1,124 @@
+"""Golden tests for the C4 builder.
+
+Each test seeds an in-memory DB with a tiny but realistic fixture
+(repository + graph_nodes + graph_edges + external_systems) and then
+asserts the shape of build_l1 / build_l2 / build_l3 output.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.persistence import (
+ batch_upsert_graph_edges,
+ batch_upsert_graph_nodes,
+ bulk_upsert_external_systems,
+ link_graph_nodes_to_external_systems,
+ upsert_repository,
+)
+from repowise.server.services import c4_builder
+
+
+async def _seed_monorepo(session):
+ """Two containers — packages/core and packages/web — with one cross-edge
+ and a single external dep on each side.
+ """
+ repo = await upsert_repository(session, name="demo", local_path="/tmp/demo")
+
+ files = [
+ "packages/core/ingestion/parser.py",
+ "packages/core/ingestion/graph.py",
+ "packages/core/persistence/models.py",
+ "packages/web/app/page.tsx",
+ "packages/web/lib/api.ts",
+ ]
+ nodes = [
+ {"node_id": f, "node_type": "file", "language": "python" if f.endswith(".py") else "typescript", "symbol_count": 1}
+ for f in files
+ ]
+ # External nodes for imports
+ nodes.append({"node_id": "external:fastapi", "node_type": "file", "language": "python", "symbol_count": 0})
+ nodes.append({"node_id": "external:react", "node_type": "file", "language": "typescript", "symbol_count": 0})
+ await batch_upsert_graph_nodes(session, repo.id, nodes)
+
+ edges = [
+ # Within container
+ {"source_node_id": "packages/core/ingestion/parser.py", "target_node_id": "packages/core/ingestion/graph.py", "edge_type": "imports"},
+ # Cross container
+ {"source_node_id": "packages/web/lib/api.ts", "target_node_id": "packages/core/persistence/models.py", "edge_type": "imports"},
+ # To externals
+ {"source_node_id": "packages/core/ingestion/parser.py", "target_node_id": "external:fastapi", "edge_type": "imports"},
+ {"source_node_id": "packages/web/app/page.tsx", "target_node_id": "external:react", "edge_type": "imports"},
+ ]
+ await batch_upsert_graph_edges(session, repo.id, edges)
+
+ externals = [
+ {"name": "fastapi", "display_name": "FastAPI", "ecosystem": "pypi", "category": "framework", "version": "0.110", "declared_in": "packages/core/pyproject.toml", "is_dev_dep": False},
+ {"name": "react", "display_name": "React", "ecosystem": "npm", "category": "framework", "version": "^18", "declared_in": "packages/web/package.json", "is_dev_dep": False},
+ ]
+ id_map = await bulk_upsert_external_systems(session, repo.id, externals)
+ name_to_id = {name: sid for (name, _), sid in id_map.items()}
+ await link_graph_nodes_to_external_systems(session, repo.id, name_to_id)
+ await session.commit()
+ return repo
+
+
+async def test_build_l1_lists_externals_and_user(async_session):
+ repo = await _seed_monorepo(async_session)
+ view = await c4_builder.build_l1(async_session, repo.id)
+
+ assert view.system.name == "demo"
+ assert [p.id for p in view.people] == ["person:user"]
+ assert {e.name for e in view.external_systems} == {"fastapi", "react"}
+ # Every external has an edge from system; plus one user→system edge
+ assert any(r.source_id == "person:user" and r.target_id == view.system.id for r in view.relations)
+ assert sum(1 for r in view.relations if r.source_id == view.system.id) == 2
+
+
+async def test_build_l2_detects_containers_and_aggregates_edges(async_session):
+ repo = await _seed_monorepo(async_session)
+ view = await c4_builder.build_l2(async_session, repo.id)
+
+ container_paths = {c.path for c in view.containers}
+ assert container_paths == {"packages/core", "packages/web"}
+
+ by_path = {c.path: c for c in view.containers}
+ assert by_path["packages/core"].language == "python"
+ assert by_path["packages/web"].language == "typescript"
+ assert by_path["packages/core"].file_count == 3
+ assert by_path["packages/web"].file_count == 2
+
+ # web → core (one file-level edge rolled up)
+ relations = {(r.source_id, r.target_id): r for r in view.relations}
+ assert ("pkg:packages/web", "pkg:packages/core") in relations
+ cross = relations[("pkg:packages/web", "pkg:packages/core")]
+ assert cross.edge_count == 1
+
+ # External edges
+ assert ("pkg:packages/core", "ext:fastapi") in relations
+ assert ("pkg:packages/web", "ext:react") in relations
+
+ # No self-loops
+ assert all(r.source_id != r.target_id for r in view.relations)
+
+
+async def test_build_l3_returns_components_and_filters_externals(async_session):
+ repo = await _seed_monorepo(async_session)
+ view = await c4_builder.build_l3(async_session, repo.id, "pkg:packages/core")
+ assert view is not None
+ assert view.container.path == "packages/core"
+ comp_names = {c.name for c in view.components}
+ assert comp_names == {"ingestion", "persistence"}
+
+ # Only fastapi should appear under L3 of packages/core (not react)
+ assert {e.name for e in view.external_systems} == {"fastapi"}
+
+
+async def test_build_l3_unknown_container_returns_none(async_session):
+ repo = await _seed_monorepo(async_session)
+ view = await c4_builder.build_l3(async_session, repo.id, "pkg:does/not/exist")
+ assert view is None
diff --git a/tests/unit/server/test_c4.py b/tests/unit/server/test_c4.py
new file mode 100644
index 000000000..fd7cac8be
--- /dev/null
+++ b/tests/unit/server/test_c4.py
@@ -0,0 +1,129 @@
+"""HTTP-level tests for /api/graph/{repo_id}/c4/{l1,l2,l3}."""
+
+from __future__ import annotations
+
+import tempfile
+from pathlib import Path
+
+from httpx import AsyncClient
+
+from repowise.core.persistence import (
+ batch_upsert_graph_edges,
+ batch_upsert_graph_nodes,
+ bulk_upsert_external_systems,
+ link_graph_nodes_to_external_systems,
+)
+
+
+async def create_test_repo(client: AsyncClient) -> dict:
+ """Local copy of tests.unit.server.conftest.create_test_repo so this
+ module collects standalone (conftest helpers are not importable as a
+ module from every pytest entry point)."""
+ repo_dir = Path(tempfile.mkdtemp()) / "test-repo"
+ repo_dir.mkdir(exist_ok=True)
+ (repo_dir / ".git").mkdir(exist_ok=True)
+ resp = await client.post(
+ "/api/repos",
+ json={
+ "name": "test-repo",
+ "local_path": str(repo_dir),
+ "url": "https://github.com/example/test-repo",
+ },
+ )
+ assert resp.status_code == 201
+ return resp.json()
+
+
+async def _seed_two_containers(client: AsyncClient, app) -> str:
+ """Create a repo + a tiny graph + 2 external deps. Returns repo_id."""
+ repo = await create_test_repo(client)
+ repo_id = repo["id"]
+
+ async with app.state.session_factory() as session:
+ nodes = [
+ {"node_id": "packages/core/parser.py", "node_type": "file", "language": "python", "symbol_count": 2},
+ {"node_id": "packages/core/graph.py", "node_type": "file", "language": "python", "symbol_count": 3},
+ {"node_id": "packages/web/page.tsx", "node_type": "file", "language": "typescript", "symbol_count": 1},
+ {"node_id": "external:fastapi", "node_type": "file", "language": "python", "symbol_count": 0},
+ {"node_id": "external:react", "node_type": "file", "language": "typescript", "symbol_count": 0},
+ ]
+ await batch_upsert_graph_nodes(session, repo_id, nodes)
+ await batch_upsert_graph_edges(session, repo_id, [
+ {"source_node_id": "packages/web/page.tsx", "target_node_id": "packages/core/graph.py", "edge_type": "imports"},
+ {"source_node_id": "packages/core/parser.py", "target_node_id": "external:fastapi", "edge_type": "imports"},
+ {"source_node_id": "packages/web/page.tsx", "target_node_id": "external:react", "edge_type": "imports"},
+ ])
+ id_map = await bulk_upsert_external_systems(session, repo_id, [
+ {"name": "fastapi", "display_name": "FastAPI", "ecosystem": "pypi", "category": "framework", "version": "0.110", "declared_in": "packages/core/pyproject.toml", "is_dev_dep": False},
+ {"name": "react", "display_name": "React", "ecosystem": "npm", "category": "framework", "version": "^18", "declared_in": "packages/web/package.json", "is_dev_dep": False},
+ ])
+ name_to_id = {n: sid for (n, _), sid in id_map.items()}
+ await link_graph_nodes_to_external_systems(session, repo_id, name_to_id)
+ await session.commit()
+ return repo_id
+
+
+async def test_l1_endpoint_returns_system_and_externals(client: AsyncClient, app) -> None:
+ repo_id = await _seed_two_containers(client, app)
+ resp = await client.get(f"/api/graph/{repo_id}/c4/l1")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["system"]["name"] == "test-repo"
+ assert [p["id"] for p in body["people"]] == ["person:user"]
+ assert {e["name"] for e in body["external_systems"]} == {"fastapi", "react"}
+ # User → system + system → 2 externals
+ assert len(body["relations"]) == 3
+
+
+async def test_l2_endpoint_returns_containers_and_aggregated_edges(client: AsyncClient, app) -> None:
+ repo_id = await _seed_two_containers(client, app)
+ resp = await client.get(f"/api/graph/{repo_id}/c4/l2")
+ assert resp.status_code == 200
+ body = resp.json()
+ paths = {c["path"] for c in body["containers"]}
+ assert paths == {"packages/core", "packages/web"}
+
+ edges = {(r["source_id"], r["target_id"]) for r in body["relations"]}
+ assert ("pkg:packages/web", "pkg:packages/core") in edges
+ assert ("pkg:packages/core", "ext:fastapi") in edges
+ assert ("pkg:packages/web", "ext:react") in edges
+
+
+async def test_l3_endpoint_requires_container_id(client: AsyncClient, app) -> None:
+ repo_id = await _seed_two_containers(client, app)
+ resp = await client.get(f"/api/graph/{repo_id}/c4/l3")
+ assert resp.status_code == 422 # missing query param
+
+
+async def test_l3_endpoint_returns_components_for_container(client: AsyncClient, app) -> None:
+ repo_id = await _seed_two_containers(client, app)
+ resp = await client.get(
+ f"/api/graph/{repo_id}/c4/l3",
+ params={"container_id": "pkg:packages/core"},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["container"]["path"] == "packages/core"
+ # All files in packages/core sit at the container root → _root component
+ comp_names = {c["name"] for c in body["components"]}
+ assert comp_names == {"_root"}
+ # Only fastapi (used from packages/core), react is filtered out
+ assert {e["name"] for e in body["external_systems"]} == {"fastapi"}
+
+
+async def test_l3_endpoint_returns_404_for_unknown_container(client: AsyncClient, app) -> None:
+ repo_id = await _seed_two_containers(client, app)
+ resp = await client.get(
+ f"/api/graph/{repo_id}/c4/l3",
+ params={"container_id": "pkg:does/not/exist"},
+ )
+ assert resp.status_code == 404
+
+
+async def test_l1_endpoint_on_empty_repo(client: AsyncClient) -> None:
+ repo = await create_test_repo(client)
+ resp = await client.get(f"/api/graph/{repo['id']}/c4/l1")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["external_systems"] == []
+ assert body["system"]["name"] == "test-repo"