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.

Workspace architecture metrics: propagation cost, core-periphery roles, and a 1-10 score (#517)

Raghav Chamadiyaed3669173e2d
diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md
index 252692ace..44551f13f 100644
--- a/docs/MCP_TOOLS.md
+++ b/docs/MCP_TOOLS.md
@@ -29,6 +29,7 @@ repowise mcp --transport sse --port 7338 # legacy SSE transport
| `get_health` | Code-health biomarker scores | Before refactoring — find the worst files |
| `get_blast_radius` | Cross-repo downstream impact (workspace only) | Before changing a service other repos consume |
| `get_conformance` | Architecture rule violations + cycles (workspace only) | Auditing or before changing service boundaries |
+| `get_architecture` | System coupling, cyclic core, 1-10 architecture score (workspace only) | Gauging overall structure before a cross-service refactor |
---
@@ -280,6 +281,24 @@ get_conformance(repo="frontend")
---
+## `get_architecture`
+
+*(Workspace mode only.)* The one evaluative read of the whole system: how coupled is it, where is the architectural core, and a single 1-10 architecture score. Deterministic, structural edges only (co-change excluded).
+
+**Parameters:** none.
+
+**Returns:** `score` (1-10), `architecture_type` (`core-periphery` or `hierarchical`), `propagation_cost_pct` (share of other services the average service reaches), `core_size` / `core_ratio` / `core_members` (the largest cyclic group), `cycle_count`, `conformance_violations`, a `role_breakdown` (count of Core / Shared / Control / Peripheral services), and a one-line `summary`.
+
+**When to use:** Before a cross-service refactor, or to gauge and compare overall system structure over time. See [Architecture Metrics](WORKSPACES.md#architecture-metrics).
+
+**Example call:**
+
+```
+get_architecture()
+```
+
+---
+
## `get_why`
Architectural decision intelligence. Three modes depending on parameters.
@@ -384,6 +403,7 @@ The MCP server automatically enriches responses with cross-repo intelligence:
- **Cross-repo blast radius** via the workspace-only `get_blast_radius` tool, and a cross-repo `directive` in `get_risk` PR-mode
- **Breaking-change guard** — incompatible provider-contract changes and the consumers they endanger, in the `get_risk` PR-mode `breaking_changes` directive
- **Architecture conformance** — declared dependency-rule violations and dependency cycles via the workspace-only `get_conformance` tool, and `conformance_violations` / `dependency_cycles` in the `get_risk` PR-mode directive
+- **Architecture metrics** — whole-system coupling (propagation cost), the cyclic core, per-service roles, and a deterministic 1-10 architecture score via the workspace-only `get_architecture` tool
---
diff --git a/docs/WORKSPACES.md b/docs/WORKSPACES.md
index db7c2f1be..27455dc61 100644
--- a/docs/WORKSPACES.md
+++ b/docs/WORKSPACES.md
@@ -11,10 +11,11 @@ Repowise workspaces let you index and analyze multiple repositories together. Yo
3. [How It Works](#how-it-works)
4. [Workspace Commands](#workspace-commands)
5. [Cross-Repo Intelligence](#cross-repo-intelligence)
-6. [Web UI](#web-ui)
-7. [MCP Integration](#mcp-integration)
-8. [File Layout](#file-layout)
-9. [FAQ](#faq)
+6. [Architecture Metrics](#architecture-metrics)
+7. [Web UI](#web-ui)
+8. [MCP Integration](#mcp-integration)
+9. [File Layout](#file-layout)
+10. [FAQ](#faq)
---
@@ -188,6 +189,15 @@ repowise workspace check # human-readable report; exit 1 on fin
repowise workspace check --json # raw report JSON
```
+### `repowise workspace metrics`
+
+Architecture-complexity metrics: propagation cost, the cyclic core, per-service roles, and a deterministic 1-10 architecture score. See [Architecture Metrics](#architecture-metrics).
+
+```bash
+repowise workspace metrics # human-readable summary
+repowise workspace metrics --json # raw metrics JSON
+```
+
---
## Cross-Repo Intelligence
@@ -402,12 +412,43 @@ Independently of any rules, conformance detects **circular dependencies** among
---
+## Architecture Metrics
+
+Conformance and the cycle finder answer *per-relationship* questions (is this edge allowed, is this loop a cycle). Architecture metrics give the one *evaluative* read of the whole system: how coupled it is, where its architectural core is, and a single score you can track over time and compare across workspaces. These are the standard MacCormack / Baldwin / Sturtevant architecture-complexity metrics, computed deterministically over the system graph — no LLM. They use **structural edges only** (http / grpc / event / package / db); co-change is excluded.
+
+### What it computes
+
+- **Propagation cost** — the share of *other* services the average service can reach transitively through dependencies (0% = fully decoupled, 100% = everything reaches everything). The headline coupling number; lower is better.
+- **Cyclic core** — the largest cyclic group of services (the largest strongly-connected component of the structural graph). Its size and ratio (core / services) describe how much of the system is tangled together.
+- **Architecture type** — `core-periphery` when the core spans a meaningful fraction of the system, else `hierarchical`.
+- **Per-service role** — each service is classified from its visibility profile:
+ - **Core** — in the largest cyclic group (the architectural center).
+ - **Shared** — high visibility fan-in, low fan-out: many services depend on it, it depends on few (a widely-used utility/library).
+ - **Control** — high fan-out, low fan-in: it depends on many, few depend on it (an orchestrator / entry point).
+ - **Peripheral** — lightly coupled in both directions.
+- **Architecture score** — a deterministic 1-10 roll-up (matching the Code Health 1-10 convention) from propagation cost, core ratio, dependency-cycle count, and declared-rule violation count. Lower coupling and a smaller core score higher.
+
+### Using it
+
+- **CLI** — `repowise workspace metrics` prints the score, propagation cost, cyclic core, dependency-cycle count, and the per-role service breakdown. CI-friendly plain output; `--json` emits the raw metrics.
+
+ ```bash
+ repowise workspace metrics # human-readable summary
+ repowise workspace metrics --json # raw metrics JSON
+ ```
+
+- **REST** — `GET /api/workspace/architecture` returns the workspace metrics plus the per-service roles. Computed at request time from the system graph (no separate artifact); the conformance violation count, if a report exists, is folded into the score.
+- **MCP** — `get_architecture` gives an agent the score, propagation cost, core members, and role breakdown in one call — the system-structure read to consult before a cross-service refactor.
+- **Web** — the **architecture score** appears as a stat on both the Conformance and System Map pages. The DSM header shows score / propagation cost / core size and tints each service's diagonal cell by its role, so the on-diagonal core block stands out. On the Live System Map, toggle **Core** to highlight the cyclic core, and the inspector shows any selected service's role and visibility profile.
+
+---
+
## MCP Integration
Workspace init automatically registers MCP servers with Claude Desktop and Claude Code. The MCP server is workspace-aware:
- **Default repo context** — queries go to the primary repo unless you specify otherwise
-- **Cross-repo tools** — MCP tools can query across repos and return enriched context with co-change and contract data; `get_blast_radius` answers cross-repo downstream impact (see [Cross-Repo Blast Radius](#cross-repo-blast-radius)); `get_conformance` answers architecture rule violations and dependency cycles (see [Architecture Conformance](#architecture-conformance))
+- **Cross-repo tools** — MCP tools can query across repos and return enriched context with co-change and contract data; `get_blast_radius` answers cross-repo downstream impact (see [Cross-Repo Blast Radius](#cross-repo-blast-radius)); `get_conformance` answers architecture rule violations and dependency cycles (see [Architecture Conformance](#architecture-conformance)); `get_architecture` answers whole-system coupling, the cyclic core, and the architecture score (see [Architecture Metrics](#architecture-metrics))
- **Repo parameter** — most tools accept an optional `repo` parameter to target a specific repo, or `"all"` to query across the workspace
---
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
index e725931ec..f90641cb9 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
@@ -1050,9 +1050,7 @@ def workspace_check(path: str | None, as_json: bool) -> None:
# Rule violations
if report.violations:
- console.print(
- f"\n[red]✗ {len(report.violations)} architecture rule violation(s):[/red]"
- )
+ console.print(f"\n[red]✗ {len(report.violations)} architecture rule violation(s):[/red]")
for v in report.violations:
rule = f"{v.rule_source} !-> {v.rule_target}"
console.print(
@@ -1072,8 +1070,7 @@ def workspace_check(path: str | None, as_json: bool) -> None:
if not report.has_findings:
if rule_count:
console.print(
- f"\n[green]✓[/green] No violations of {rule_count} rule(s); "
- "no dependency cycles."
+ f"\n[green]✓[/green] No violations of {rule_count} rule(s); no dependency cycles."
)
else:
console.print("\n[green]✓[/green] No dependency cycles.")
@@ -1084,3 +1081,101 @@ def workspace_check(path: str | None, as_json: bool) -> None:
f"{len(report.cycles)} cycle(s)."
)
sys.exit(1)
+
+
+# ---------------------------------------------------------------------------
+# workspace metrics
+# ---------------------------------------------------------------------------
+
+
+@workspace_group.command("metrics")
[email protected]("path", required=False, default=None)
[email protected]("--json", "as_json", is_flag=True, help="Emit the raw metrics as JSON.")
+def workspace_metrics(path: str | None, as_json: bool) -> None:
+ """Architecture metrics — propagation cost, core, and a 1-10 score.
+
+ Computes the standard architecture-complexity metrics over the system graph
+ built by 'repowise update --workspace': how coupled the whole system is
+ (propagation cost), which services form the cyclic core, and a single
+ deterministic 1-10 score. Uses structural edges only; co-change is excluded.
+ Declared-rule violations, if any, are folded into the score. CI-friendly
+ plain output.
+ """
+ import json as _json
+
+ from repowise.core.workspace.architecture_metrics import compute_architecture_metrics
+ from repowise.core.workspace.conformance import (
+ check_conformance,
+ tags_by_repo_from_config,
+ )
+ from repowise.core.workspace.system_graph import load_system_graph
+
+ start = resolve_repo_path(path)
+ ws_root, ws_config = _require_workspace(start)
+
+ graph = load_system_graph(ws_root)
+ if graph is None:
+ raise click.ClickException(
+ "No system graph found. Run 'repowise update --workspace' to build "
+ "cross-repo relationships first."
+ )
+
+ violations = check_conformance(
+ graph, ws_config.conformance.rules, tags_by_repo_from_config(ws_config)
+ )
+ metrics = compute_architecture_metrics(
+ graph,
+ conformance_violations=len(violations),
+ generated_at=graph.generated_at,
+ )
+
+ if as_json:
+ console.print_json(_json.dumps(metrics.to_dict()))
+ return
+
+ if metrics.node_count == 0:
+ console.print(
+ "[dim]No services in the system graph yet.[/dim] Run "
+ "'repowise update --workspace' after indexing repos with cross-repo "
+ "relationships."
+ )
+ return
+
+ score_color = "green" if metrics.score >= 8 else "yellow" if metrics.score >= 4 else "red"
+ console.print(
+ f"\n Architecture score [bold {score_color}]{metrics.score:.1f}[/bold {score_color}]"
+ f" / 10 [dim]({metrics.architecture_type})[/dim]"
+ )
+ console.print(
+ f" Propagation cost [bold]{metrics.propagation_cost_pct:.1f}%[/bold]"
+ f" [dim]avg share of other services each one can reach[/dim]"
+ )
+ if metrics.core_size:
+ members = ", ".join(metrics.core_members[:6])
+ if len(metrics.core_members) > 6:
+ members += f", +{len(metrics.core_members) - 6} more"
+ console.print(
+ f" Cyclic core [bold]{metrics.core_size}[/bold] service(s)"
+ f" ([dim]{metrics.core_ratio * 100:.0f}% of {metrics.node_count}[/dim]) — {members}"
+ )
+ else:
+ console.print(
+ f" Cyclic core [green]none[/green]"
+ f" [dim]({metrics.node_count} services, acyclic structure)[/dim]"
+ )
+ console.print(f" Dependency cycles [bold]{metrics.cycle_count}[/bold]")
+ if metrics.conformance_violations:
+ console.print(
+ f" Rule violations [red]{metrics.conformance_violations}[/red]"
+ f" [dim](folded into the score)[/dim]"
+ )
+
+ breakdown = metrics.role_breakdown()
+ role_labels = {
+ "core": "Core",
+ "shared": "Shared",
+ "control": "Control",
+ "peripheral": "Peripheral",
+ }
+ parts = ", ".join(f"{role_labels[r]} {breakdown.get(r, 0)}" for r in role_labels)
+ console.print(f"\n Service roles: {parts}")
diff --git a/packages/core/src/repowise/core/workspace/__init__.py b/packages/core/src/repowise/core/workspace/__init__.py
index 377bcee5a..4c5ec8242 100644
--- a/packages/core/src/repowise/core/workspace/__init__.py
+++ b/packages/core/src/repowise/core/workspace/__init__.py
@@ -69,6 +69,12 @@ from .system_graph import (
run_system_graph_build,
save_system_graph,
)
+from .architecture_metrics import (
+ ArchitectureMetrics,
+ NodeArchitectureRole,
+ architecture_score,
+ compute_architecture_metrics,
+)
__all__ = [
# Scanner
@@ -127,4 +133,9 @@ __all__ = [
"load_system_graph",
"run_system_graph_build",
"save_system_graph",
+ # Architecture metrics (Phase 6)
+ "ArchitectureMetrics",
+ "NodeArchitectureRole",
+ "architecture_score",
+ "compute_architecture_metrics",
]
diff --git a/packages/core/src/repowise/core/workspace/architecture_metrics.py b/packages/core/src/repowise/core/workspace/architecture_metrics.py
new file mode 100644
index 000000000..618381526
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/architecture_metrics.py
@@ -0,0 +1,475 @@
+"""Architecture-complexity metrics over the workspace system graph.
+
+A workspace can already see every service, every typed edge, every cycle, and
+every conformance violation. What it cannot get from those descriptive views is
+a single *evaluative* read: how coupled is the whole system, and which services
+form its architectural core. This module computes the standard
+MacCormack / Baldwin / Sturtevant complexity metrics over the
+:class:`~repowise.core.workspace.system_graph.SystemGraph` every other workspace
+view reads, and rolls them into one deterministic 1-10 architecture score.
+
+**Three outputs, one pass:**
+
+* *Per workspace* — propagation cost, core size and ratio, cycle count, an
+ architecture-type label (core-periphery vs hierarchical), and the score.
+* *Per service* — visibility fan-in / fan-out and a core-periphery role
+ (Core / Shared / Control / Peripheral).
+* *Benchmarkable numbers* — propagation cost and the score are comparable across
+ workspaces and over time.
+
+**Structural edges only.** Visibility is the transitive closure over the
+``edge.structural`` edges (http / grpc / event / package / db) — co-change is
+behavioral and never asserts a dependency, so it is excluded from every metric
+here. The structural/behavioral distinction is the one the system graph already
+encodes (see :data:`system_graph._STRUCTURAL_KINDS`).
+
+**Reuse, not reinvention.** The largest cyclic group is the largest
+strongly-connected component, computed with NetworkX (the same library
+:mod:`cycles` and the single-repo graph metrics use). The cycle *count* fed into
+the score is :func:`cycles.detect_cycles`, so the number matches what the DSM and
+the conformance report already show. No second cycle/SCC implementation, no LLM.
+
+Pure and I/O-free: it consumes a ``SystemGraph`` (plus an optional
+already-computed conformance violation count) and returns dataclasses.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass, field
+from statistics import median
+from typing import Any
+
+from repowise.core.workspace.cycles import detect_cycles
+from repowise.core.workspace.system_graph import SystemEdge, SystemGraph
+
+_log = logging.getLogger("repowise.workspace.architecture_metrics")
+
+# ---------------------------------------------------------------------------
+# Tuning constants (single source of truth)
+#
+# Every weight, cap, and cutoff the metric depends on lives here — no magic
+# numbers scattered across the functions below. Lower coupling and a smaller
+# cyclic core always map to a *higher* score.
+# ---------------------------------------------------------------------------
+
+#: Score bounds. Matches the Code Health 1-10 convention (a 0 is never shown).
+SCORE_MAX = 10.0
+SCORE_MIN = 1.0
+
+#: Points subtracted from :data:`SCORE_MAX` per driver. The propagation-cost and
+#: core-ratio terms scale with their 0-1 fractions; the cycle and violation terms
+#: accrue per finding up to a cap so a pathological tangle can't drive the score
+#: arbitrarily negative before clamping.
+PROPAGATION_COST_WEIGHT = 5.0 # full reachability (pc = 1.0) costs 5 points
+CORE_RATIO_WEIGHT = 3.0 # the whole system in one cyclic core costs 3 points
+CYCLE_PENALTY_PER = 0.5 # per elementary dependency cycle
+CYCLE_PENALTY_CAP = 2.0
+VIOLATION_PENALTY_PER = 0.5 # per declared-rule conformance violation
+VIOLATION_PENALTY_CAP = 2.0
+
+#: A system whose largest cyclic group spans at least this fraction of its
+#: services is "core-periphery"; below it the dependency structure is
+#: "hierarchical". Roughly matches the empirical large-core threshold in the
+#: MacCormack/Baldwin studies.
+CORE_PERIPHERY_MIN_RATIO = 0.06
+
+#: Core-periphery role labels (the one place they are spelled).
+ROLE_CORE = "core"
+ROLE_SHARED = "shared"
+ROLE_CONTROL = "control"
+ROLE_PERIPHERAL = "peripheral"
+ROLE_ORDER: tuple[str, ...] = (ROLE_CORE, ROLE_SHARED, ROLE_CONTROL, ROLE_PERIPHERAL)
+
+#: Architecture-type labels.
+ARCH_CORE_PERIPHERY = "core-periphery"
+ARCH_HIERARCHICAL = "hierarchical"
+
+
+# ---------------------------------------------------------------------------
+# Data models
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class NodeArchitectureRole:
+ """Per-service architectural role and its visibility profile.
+
+ ``visibility_fan_out`` is the number of services this one can reach through
+ structural dependencies (its row sum in the visibility matrix, counting
+ itself); ``visibility_fan_in`` is the number that can reach it (its column
+ sum). ``role`` is the core-periphery classification.
+ """
+
+ id: str
+ repo: str
+ name: str
+ visibility_fan_in: int
+ visibility_fan_out: int
+ role: str # core | shared | control | peripheral
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "id": self.id,
+ "repo": self.repo,
+ "name": self.name,
+ "visibility_fan_in": self.visibility_fan_in,
+ "visibility_fan_out": self.visibility_fan_out,
+ "role": self.role,
+ }
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> NodeArchitectureRole:
+ return cls(
+ id=data["id"],
+ repo=data.get("repo", ""),
+ name=data.get("name", data["id"]),
+ visibility_fan_in=data.get("visibility_fan_in", 0),
+ visibility_fan_out=data.get("visibility_fan_out", 0),
+ role=data.get("role", ROLE_PERIPHERAL),
+ )
+
+
+@dataclass
+class ArchitectureMetrics:
+ """The whole-workspace architecture-complexity read.
+
+ ``propagation_cost`` is the fraction of *other* services the average service
+ can reach transitively (0 = fully decoupled, 1 = everything reaches
+ everything). ``core_*`` describe the largest cyclic group. ``score`` is the
+ deterministic 1-10 roll-up; ``roles`` carries the per-service breakdown.
+ """
+
+ node_count: int
+ structural_edge_count: int
+ propagation_cost: float # 0-1 fraction
+ propagation_cost_pct: float # percentage, 1 decimal — for display
+ core_size: int
+ core_ratio: float # core_size / node_count
+ core_members: list[str]
+ cycle_count: int
+ conformance_violations: int
+ architecture_type: str # core-periphery | hierarchical
+ score: float # 1-10
+ roles: list[NodeArchitectureRole] = field(default_factory=list)
+ generated_at: str = ""
+
+ def role_breakdown(self) -> dict[str, int]:
+ """Count of services per role, in canonical role order."""
+ counts = {role: 0 for role in ROLE_ORDER}
+ for r in self.roles:
+ counts[r.role] = counts.get(r.role, 0) + 1
+ return counts
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "node_count": self.node_count,
+ "structural_edge_count": self.structural_edge_count,
+ "propagation_cost": self.propagation_cost,
+ "propagation_cost_pct": self.propagation_cost_pct,
+ "core_size": self.core_size,
+ "core_ratio": self.core_ratio,
+ "core_members": self.core_members,
+ "cycle_count": self.cycle_count,
+ "conformance_violations": self.conformance_violations,
+ "architecture_type": self.architecture_type,
+ "score": self.score,
+ "role_breakdown": self.role_breakdown(),
+ "roles": [r.to_dict() for r in self.roles],
+ "generated_at": self.generated_at,
+ }
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> ArchitectureMetrics:
+ return cls(
+ node_count=data.get("node_count", 0),
+ structural_edge_count=data.get("structural_edge_count", 0),
+ propagation_cost=data.get("propagation_cost", 0.0),
+ propagation_cost_pct=data.get("propagation_cost_pct", 0.0),
+ core_size=data.get("core_size", 0),
+ core_ratio=data.get("core_ratio", 0.0),
+ core_members=list(data.get("core_members", [])),
+ cycle_count=data.get("cycle_count", 0),
+ conformance_violations=data.get("conformance_violations", 0),
+ architecture_type=data.get("architecture_type", ARCH_HIERARCHICAL),
+ score=data.get("score", SCORE_MAX),
+ roles=[NodeArchitectureRole.from_dict(r) for r in data.get("roles", [])],
+ generated_at=data.get("generated_at", ""),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Visibility (reachability) matrix — structural edges only
+# ---------------------------------------------------------------------------
+
+
+def _structural_adjacency(edges: list[SystemEdge]) -> dict[str, set[str]]:
+ """Forward dependency adjacency over structural edges: ``source -> {targets}``.
+
+ Direction is the system graph's own: ``source`` depends on / calls
+ ``target``. Behavioral co-change edges are excluded — they assert correlated
+ change, not a dependency, so they never contribute to reachability.
+ """
+ adj: dict[str, set[str]] = {}
+ for edge in edges:
+ if not edge.structural:
+ continue
+ adj.setdefault(edge.source, set()).add(edge.target)
+ return adj
+
+
+def _reachable(start: str, adj: dict[str, set[str]], node_ids: set[str]) -> set[str]:
+ """Cycle-safe transitive closure from *start*, including ``start`` itself.
+
+ A plain DFS with a visited set — the graph is service-granular (tens of
+ nodes) so this is cheap, and the visited set makes cycles terminate.
+ """
+ seen: set[str] = {start}
+ stack = [start]
+ while stack:
+ cur = stack.pop()
+ for nxt in adj.get(cur, set()):
+ if nxt in node_ids and nxt not in seen:
+ seen.add(nxt)
+ stack.append(nxt)
+ return seen
+
+
+def _visibility_matrix(node_ids: list[str], adj: dict[str, set[str]]) -> dict[str, set[str]]:
+ """Reachable set (including self) for every node, keyed by node id."""
+ valid = set(node_ids)
+ return {nid: _reachable(nid, adj, valid) for nid in node_ids}
+
+
+# ---------------------------------------------------------------------------
+# Core (largest cyclic group = largest SCC of the structural graph)
+# ---------------------------------------------------------------------------
+
+
+def _largest_cyclic_core(node_ids: list[str], adj: dict[str, set[str]]) -> list[str]:
+ """Return the members of the largest cyclic group, or ``[]`` if acyclic.
+
+ The largest cyclic group is the largest strongly-connected component of the
+ structural dependency graph with at least two members (a lone service is not
+ a cycle). Delegated to NetworkX — the same SCC routine the rest of the
+ codebase relies on; no hand-rolled Tarjan here. Ties broken lexicographically
+ on the sorted member list so the result is deterministic.
+ """
+ try:
+ import networkx as nx
+ except Exception: # pragma: no cover - networkx is a hard dependency
+ _log.warning("networkx unavailable; skipping core detection", exc_info=True)
+ return []
+
+ digraph = nx.DiGraph()
+ digraph.add_nodes_from(node_ids)
+ for src, targets in adj.items():
+ for tgt in targets:
+ digraph.add_edge(src, tgt)
+
+ best: list[str] = []
+ for component in nx.strongly_connected_components(digraph):
+ if len(component) < 2:
+ continue # a single node (even self-looping) is not a cyclic group
+ members = sorted(component)
+ if len(members) > len(best) or (len(members) == len(best) and members < best):
+ best = members
+ return best
+
+
+# ---------------------------------------------------------------------------
+# Core-periphery role classification
+# ---------------------------------------------------------------------------
+
+
+def _classify_role(
+ vfi: int,
+ vfo: int,
+ *,
+ is_core: bool,
+ threshold_fi: float,
+ threshold_fo: float,
+) -> str:
+ """Assign one core-periphery role from a node's visibility profile.
+
+ * **Core** — a member of the largest cyclic group.
+ * **Shared** — visibility fan-in at or above the threshold but fan-out below
+ it: many services reach it, it reaches few (a widely-used library/utility).
+ * **Control** — fan-out at or above but fan-in below: it reaches many, few
+ reach it (an orchestrator / entry point).
+ * **Peripheral** — neither, including services that touch only themselves.
+
+ The threshold is the core's own visibility floor when a core exists (so a
+ non-core node is judged "as visible as the core"), else the median across all
+ services (so an acyclic system still splits sensibly).
+ """
+ if is_core:
+ return ROLE_CORE
+ # Isolated services (reach and are reached by only themselves) are always
+ # peripheral, regardless of thresholds — guards single-service workspaces.
+ if vfi <= 1 and vfo <= 1:
+ return ROLE_PERIPHERAL
+
+ hi_fi = vfi >= threshold_fi
+ hi_fo = vfo >= threshold_fo
+ if hi_fi and not hi_fo:
+ return ROLE_SHARED
+ if hi_fo and not hi_fi:
+ return ROLE_CONTROL
+ if hi_fi and hi_fo:
+ # A would-be core that is not actually cyclic: lean to its dominant axis.
+ return ROLE_SHARED if vfi >= vfo else ROLE_CONTROL
+ return ROLE_PERIPHERAL
+
+
+# ---------------------------------------------------------------------------
+# Score
+# ---------------------------------------------------------------------------
+
+
+def _clamp(value: float, low: float, high: float) -> float:
+ return max(low, min(high, value))
+
+
+def architecture_score(
+ propagation_cost: float,
+ core_ratio: float,
+ cycle_count: int,
+ conformance_violations: int,
+) -> float:
+ """Roll the drivers into a deterministic 1-10 score (1 decimal place).
+
+ See the constants block for every weight and cap. Lower coupling, a smaller
+ cyclic core, fewer cycles, and fewer rule violations all raise the score.
+ """
+ penalty = (
+ PROPAGATION_COST_WEIGHT * propagation_cost
+ + CORE_RATIO_WEIGHT * core_ratio
+ + min(CYCLE_PENALTY_CAP, CYCLE_PENALTY_PER * cycle_count)
+ + min(VIOLATION_PENALTY_CAP, VIOLATION_PENALTY_PER * conformance_violations)
+ )
+ return round(_clamp(SCORE_MAX - penalty, SCORE_MIN, SCORE_MAX), 1)
+
+
+# ---------------------------------------------------------------------------
+# Public entry point
+# ---------------------------------------------------------------------------
+
+
+def compute_architecture_metrics(
+ graph: SystemGraph,
+ *,
+ conformance_violations: int = 0,
+ generated_at: str = "",
+) -> ArchitectureMetrics:
+ """Compute the workspace architecture metrics from *graph*.
+
+ Pure. ``conformance_violations`` is supplied by the caller (from the already
+ computed conformance report) so this module stays independent of rule
+ evaluation; pass 0 when no rules are declared. ``generated_at`` is stamped
+ through unchanged for the artifact/response.
+ """
+ node_ids = [n.id for n in graph.nodes]
+ n = len(node_ids)
+
+ adj = _structural_adjacency(graph.edges)
+ structural_edge_count = sum(len(t) for t in adj.values())
+
+ # Empty / single-service workspaces are vacuously decoupled — no coupling is
+ # possible, so the score is the maximum and there is no core.
+ if n <= 1:
+ roles = [
+ NodeArchitectureRole(
+ id=node.id,
+ repo=node.repo,
+ name=node.name,
+ visibility_fan_in=1,
+ visibility_fan_out=1,
+ role=ROLE_PERIPHERAL,
+ )
+ for node in graph.nodes
+ ]
+ return ArchitectureMetrics(
+ node_count=n,
+ structural_edge_count=structural_edge_count,
+ propagation_cost=0.0,
+ propagation_cost_pct=0.0,
+ core_size=0,
+ core_ratio=0.0,
+ core_members=[],
+ cycle_count=0,
+ conformance_violations=conformance_violations,
+ architecture_type=ARCH_HIERARCHICAL,
+ score=SCORE_MAX,
+ roles=roles,
+ generated_at=generated_at,
+ )
+
+ visibility = _visibility_matrix(node_ids, adj)
+ vfo = {nid: len(reach) for nid, reach in visibility.items()}
+ vfi = {nid: 0 for nid in node_ids}
+ for reach in visibility.values():
+ for target in reach:
+ vfi[target] += 1
+
+ # Propagation cost: off-diagonal density of the visibility matrix — the
+ # fraction of *other* services the average service can reach. Excluding the
+ # diagonal keeps the metric 0 for a fully decoupled system of any size.
+ total_visibility = sum(vfo.values())
+ off_diagonal = total_visibility - n # drop each node's reach-to-self
+ denominator = n * (n - 1)
+ propagation_cost = off_diagonal / denominator if denominator else 0.0
+
+ core_members = _largest_cyclic_core(node_ids, adj)
+ core_set = set(core_members)
+ core_size = len(core_members)
+ core_ratio = core_size / n if n else 0.0
+
+ # Role thresholds: the core's visibility floor when a core exists, else the
+ # median across all services.
+ if core_members:
+ threshold_fi = float(min(vfi[m] for m in core_members))
+ threshold_fo = float(min(vfo[m] for m in core_members))
+ else:
+ threshold_fi = float(median(vfi[nid] for nid in node_ids))
+ threshold_fo = float(median(vfo[nid] for nid in node_ids))
+
+ roles = [
+ NodeArchitectureRole(
+ id=node.id,
+ repo=node.repo,
+ name=node.name,
+ visibility_fan_in=vfi[node.id],
+ visibility_fan_out=vfo[node.id],
+ role=_classify_role(
+ vfi[node.id],
+ vfo[node.id],
+ is_core=node.id in core_set,
+ threshold_fi=threshold_fi,
+ threshold_fo=threshold_fo,
+ ),
+ )
+ for node in graph.nodes
+ ]
+
+ cycle_count = len(detect_cycles(graph))
+ score = architecture_score(propagation_cost, core_ratio, cycle_count, conformance_violations)
+ architecture_type = (
+ ARCH_CORE_PERIPHERY if core_ratio >= CORE_PERIPHERY_MIN_RATIO else ARCH_HIERARCHICAL
+ )
+
+ return ArchitectureMetrics(
+ node_count=n,
+ structural_edge_count=structural_edge_count,
+ propagation_cost=round(propagation_cost, 4),
+ propagation_cost_pct=round(propagation_cost * 100, 1),
+ core_size=core_size,
+ core_ratio=round(core_ratio, 4),
+ core_members=core_members,
+ cycle_count=cycle_count,
+ conformance_violations=conformance_violations,
+ architecture_type=architecture_type,
+ score=score,
+ roles=roles,
+ generated_at=generated_at,
+ )
diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.py
index 9ccacaca4..7e95dfafa 100644
--- a/packages/server/src/repowise/server/mcp_server/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/__init__.py
@@ -38,6 +38,7 @@ from repowise.server.mcp_server._server import (
run_mcp,
)
from repowise.server.mcp_server.tool_answer import get_answer
+from repowise.server.mcp_server.tool_architecture import get_architecture
from repowise.server.mcp_server.tool_blast_radius import get_blast_radius
from repowise.server.mcp_server.tool_conformance import get_conformance
from repowise.server.mcp_server.tool_context import get_context
@@ -110,6 +111,7 @@ __all__ = [
"_is_path",
"create_mcp_server",
"get_answer",
+ "get_architecture",
"get_blast_radius",
"get_conformance",
"get_context",
diff --git a/packages/server/src/repowise/server/mcp_server/_enrichment.py b/packages/server/src/repowise/server/mcp_server/_enrichment.py
index b34b28300..c536fc83e 100644
--- a/packages/server/src/repowise/server/mcp_server/_enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/_enrichment.py
@@ -340,6 +340,31 @@ class CrossRepoEnricher:
]
return {"violations": violations, "cycles": cycles}
+ def get_architecture_metrics(self) -> dict | None:
+ """Compute the architecture-complexity metrics from the system graph.
+
+ Pure read over the already-loaded ``system_graph`` (structural edges
+ only); the conformance violation count, if a report is loaded, is folded
+ into the score. Returns ``None`` when no system graph is available.
+ """
+ if self._system_graph is None:
+ return None
+ from repowise.core.workspace.architecture_metrics import (
+ compute_architecture_metrics,
+ )
+ from repowise.core.workspace.system_graph import SystemGraph
+
+ graph = SystemGraph.from_dict(self._system_graph)
+ violations = 0
+ if self._conformance:
+ violations = int(self._conformance.get("violation_count", 0))
+ metrics = compute_architecture_metrics(
+ graph,
+ conformance_violations=violations,
+ generated_at=self._system_graph.get("generated_at", ""),
+ )
+ return metrics.to_dict()
+
def get_diagnostics(self) -> dict | None:
"""Return just the extraction diagnostics block of the system graph."""
if self._system_graph is None:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_architecture.py b/packages/server/src/repowise/server/mcp_server/tool_architecture.py
new file mode 100644
index 000000000..b905f680b
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_architecture.py
@@ -0,0 +1,83 @@
+"""MCP Tool: get_architecture — workspace architecture-complexity metrics.
+
+Answers "how coupled is this whole system, and which services are its
+architectural core?" with the standard complexity metrics over the system graph:
+propagation cost, the cyclic core, per-service core-periphery roles, and a single
+deterministic 1-10 architecture score. Read-only; the full payload is also on
+``GET /api/workspace/architecture``.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from repowise.core.registry import mcp_tool_registry as mcp
+from repowise.server.mcp_server import _state
+from repowise.server.mcp_server._helpers import _is_workspace_mode
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+
+#: Cap the per-role member lists in the agent payload; full roles are on REST.
+_MCP_CORE_MEMBER_LIMIT = 25
+
+
+async def get_architecture() -> dict[str, Any]:
+ """Workspace architecture metrics — coupling, core, and a 1-10 score.
+
+ Workspace-only. Reports propagation cost (the share of other services the
+ average service can reach transitively), the largest cyclic core, the
+ core-periphery role breakdown, and a deterministic 1-10 architecture score
+ (higher = lower coupling, smaller core). Call to gauge overall system
+ structure before a cross-service refactor, or to compare against a prior
+ snapshot. Structural edges only; co-change is excluded.
+ """
+ if not _is_workspace_mode():
+ return {
+ "error": "get_architecture is only available in workspace mode.",
+ "_meta": _build_meta(),
+ }
+
+ enricher = _state._cross_repo_enricher
+ metrics = enricher.get_architecture_metrics() if enricher is not None else None
+ if not metrics:
+ return {
+ "error": (
+ "No system graph is available yet. Run `repowise update --workspace` "
+ "to build cross-repo relationships first."
+ ),
+ "_meta": _build_meta(),
+ }
+
+ core_members = metrics.get("core_members", [])
+ shown_core = core_members[:_MCP_CORE_MEMBER_LIMIT]
+ breakdown = metrics.get("role_breakdown", {})
+
+ if metrics.get("core_size", 0):
+ core_phrase = (
+ f"a cyclic core of {metrics['core_size']} service(s) "
+ f"({metrics.get('core_ratio', 0) * 100:.0f}% of the system)"
+ )
+ else:
+ core_phrase = "no cyclic core (acyclic structure)"
+ summary = (
+ f"Architecture score {metrics.get('score', 0)}/10 "
+ f"({metrics.get('architecture_type', 'hierarchical')}): propagation cost "
+ f"{metrics.get('propagation_cost_pct', 0)}%, {core_phrase}, "
+ f"{metrics.get('cycle_count', 0)} dependency cycle(s)."
+ )
+
+ return {
+ "score": metrics.get("score", 0.0),
+ "architecture_type": metrics.get("architecture_type", "hierarchical"),
+ "propagation_cost_pct": metrics.get("propagation_cost_pct", 0.0),
+ "node_count": metrics.get("node_count", 0),
+ "core_size": metrics.get("core_size", 0),
+ "core_ratio": metrics.get("core_ratio", 0.0),
+ "core_members": shown_core,
+ "core_members_truncated": max(0, len(core_members) - len(shown_core)),
+ "cycle_count": metrics.get("cycle_count", 0),
+ "conformance_violations": metrics.get("conformance_violations", 0),
+ "role_breakdown": breakdown,
+ "summary": summary,
+ "_meta": _build_meta(),
+ }
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index cb54c5885..7d3f7561f 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -20,6 +20,7 @@ from repowise.server.deps import (
verify_api_key,
)
from repowise.server.schemas import (
+ WorkspaceArchitectureResponse,
WorkspaceBlastRadiusResponse,
WorkspaceBreakingChangesResponse,
WorkspaceCoChangeEntry,
@@ -677,6 +678,48 @@ async def get_conformance(
)
+# ---------------------------------------------------------------------------
+# GET /api/workspace/architecture
+# ---------------------------------------------------------------------------
+
+
[email protected]("/architecture", response_model=WorkspaceArchitectureResponse)
+async def get_architecture(
+ ws_config=Depends(get_workspace_config),
+ enricher=Depends(get_cross_repo_enricher),
+):
+ """Architecture-complexity metrics — propagation cost, core, and a 1-10 score.
+
+ Computed at request time from the same ``system_graph.json`` artifact the map
+ renders, using structural edges only (co-change is excluded). The declared-rule
+ violation count, if a conformance report exists, is folded into the score.
+ Deterministic and LLM-free. Returns empty metrics (not 404) when no graph is
+ built yet.
+ """
+ _require_workspace(ws_config)
+
+ from repowise.core.workspace.architecture_metrics import compute_architecture_metrics
+ from repowise.core.workspace.system_graph import SystemGraph
+
+ raw = enricher.get_system_graph() if enricher is not None else None
+ if not raw:
+ return WorkspaceArchitectureResponse()
+
+ graph = SystemGraph.from_dict(raw)
+
+ # Fold in the conformance violation count when a report exists — the metric is
+ # otherwise independent of rule evaluation.
+ conformance = enricher.get_conformance() if enricher is not None else None
+ violations = int(conformance.get("violation_count", 0)) if conformance else 0
+
+ metrics = compute_architecture_metrics(
+ graph,
+ conformance_violations=violations,
+ generated_at=raw.get("generated_at", ""),
+ )
+ return WorkspaceArchitectureResponse(**metrics.to_dict())
+
+
# ---------------------------------------------------------------------------
# POST /api/workspace/sync
# ---------------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index f7996843f..0288b30ca 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -155,6 +155,7 @@ from .ui_helpers import (
WebhookResponse,
)
from .workspace import (
+ WorkspaceArchitectureResponse,
WorkspaceBlastRadiusResponse,
WorkspaceBreakingChange,
WorkspaceBreakingChangesResponse,
@@ -306,6 +307,7 @@ __all__ = [
"WorkspaceBreakingChangesResponse",
"WorkspaceImpactedConsumer",
"WorkspaceCoChangesResponse",
+ "WorkspaceArchitectureResponse",
"WorkspaceConformanceResponse",
"WorkspaceConformanceViolation",
"WorkspaceContractEntry",
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index 2c91d0a6c..753e22b56 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -323,3 +323,31 @@ class WorkspaceConformanceResponse(BaseModel):
violation_count: int = 0
cycle_count: int = 0
violating_repos: list[str] = []
+
+
+class WorkspaceNodeArchitectureRole(BaseModel):
+ id: str
+ repo: str = ""
+ name: str = ""
+ visibility_fan_in: int = 0
+ visibility_fan_out: int = 0
+ role: str = "peripheral"
+
+
+class WorkspaceArchitectureResponse(BaseModel):
+ """Architecture-complexity metrics over the system graph (Phase 6)."""
+
+ node_count: int = 0
+ structural_edge_count: int = 0
+ propagation_cost: float = 0.0
+ propagation_cost_pct: float = 0.0
+ core_size: int = 0
+ core_ratio: float = 0.0
+ core_members: list[str] = []
+ cycle_count: int = 0
+ conformance_violations: int = 0
+ architecture_type: str = "hierarchical"
+ score: float = 10.0
+ role_breakdown: dict[str, int] = {}
+ roles: list[WorkspaceNodeArchitectureRole] = []
+ generated_at: str = ""
diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.ts
index 175a0ad1c..d71c0c6cb 100644
--- a/packages/types/src/workspace.ts
+++ b/packages/types/src/workspace.ts
@@ -378,3 +378,56 @@ export interface DsmMatrix {
/** Row-major cells: `cells[i][j]` is the dependency of `axis[i]` on `axis[j]`. */
cells: DsmCell[][];
}
+
+// ---------------------------------------------------------------------------
+// Architecture metrics (Phase 6) — the standard architecture-complexity read
+// over the system graph: propagation cost, core-periphery roles, and one
+// deterministic 1-10 score. Structural edges only; co-change is excluded.
+// Mirror of `core/workspace/architecture_metrics.py`.
+// ---------------------------------------------------------------------------
+
+/** A service's core-periphery role. */
+export type NodeRole = "core" | "shared" | "control" | "peripheral";
+
+/** Whether the dependency structure is core-periphery or hierarchical. */
+export type ArchitectureType = "core-periphery" | "hierarchical";
+
+/** Per-service architectural role and visibility profile. */
+export interface NodeArchitectureRole {
+ id: string;
+ repo: string;
+ name: string;
+ /** Services that can reach this one (column sum of the visibility matrix). */
+ visibility_fan_in: number;
+ /** Services this one can reach (row sum of the visibility matrix). */
+ visibility_fan_out: number;
+ role: NodeRole;
+}
+
+/** The whole-workspace architecture-complexity metrics. */
+export interface ArchitectureMetrics {
+ node_count: number;
+ /** Count of structural (dependency) edges the metrics were computed over. */
+ structural_edge_count: number;
+ /** Fraction (0-1) of other services the average service can reach. */
+ propagation_cost: number;
+ /** `propagation_cost` as a percentage, 1 decimal — for display. */
+ propagation_cost_pct: number;
+ /** Size of the largest cyclic group (largest SCC ≥ 2). */
+ core_size: number;
+ /** `core_size / node_count`. */
+ core_ratio: number;
+ /** Service ids in the largest cyclic group. */
+ core_members: string[];
+ /** Elementary dependency cycles (matches the conformance report's count). */
+ cycle_count: number;
+ /** Declared-rule violations folded into the score (0 when no rules). */
+ conformance_violations: number;
+ architecture_type: ArchitectureType;
+ /** Deterministic 1-10 architecture score (higher = lower coupling). */
+ score: number;
+ /** Count of services per role. */
+ role_breakdown: Record<NodeRole, number>;
+ roles: NodeArchitectureRole[];
+ generated_at: string;
+}
diff --git a/packages/ui/src/workspace/dsm/dsm-matrix.tsx b/packages/ui/src/workspace/dsm/dsm-matrix.tsx
index a78a6da8e..d4304dea0 100644
--- a/packages/ui/src/workspace/dsm/dsm-matrix.tsx
+++ b/packages/ui/src/workspace/dsm/dsm-matrix.tsx
@@ -11,12 +11,19 @@
*/
import { useMemo, useState } from "react";
-import type { DsmCell, DsmMatrix } from "@repowise-dev/types";
+import type { ArchitectureMetrics, DsmCell, DsmMatrix, NodeRole } from "@repowise-dev/types";
import { EmptyState } from "../../shared/empty-state";
import { edgeKindStyle } from "../system-map/edge-kinds";
+import { roleStyle } from "../system-map/architecture";
export interface DsmMatrixViewProps {
matrix: DsmMatrix;
+ /**
+ * Optional architecture metrics (Phase 6). When present, the header shows the
+ * score / propagation cost / core size and the diagonal is tinted by each
+ * service's core-periphery role, making the cyclic core block obvious.
+ */
+ metrics?: ArchitectureMetrics;
/** Optional click handler for a present cell (drill to the dependency). */
onSelectCell?: (cell: DsmCell) => void;
}
@@ -24,8 +31,13 @@ export interface DsmMatrixViewProps {
const CELL = 30;
const HEADER = 150;
-function cellBackground(cell: DsmCell, isDiagonal: boolean): string {
- if (isDiagonal) return "var(--color-bg-subtle)";
+function cellBackground(cell: DsmCell, isDiagonal: boolean, role?: NodeRole): string {
+ if (isDiagonal) {
+ // The diagonal is a service vs itself — repurpose it to surface the
+ // service's architecture role so the on-diagonal core block stands out.
+ if (role) return `color-mix(in srgb, ${roleStyle(role).color} 38%, transparent)`;
+ return "var(--color-bg-subtle)";
+ }
if (!cell.present) return "transparent";
if (cell.violation) return "color-mix(in srgb, var(--color-risk-high) 28%, transparent)";
if (cell.cycle) return "color-mix(in srgb, var(--color-warning) 26%, transparent)";
@@ -39,7 +51,7 @@ function cellRing(cell: DsmCell): string {
return "none";
}
-export function DsmMatrixView({ matrix, onSelectCell }: DsmMatrixViewProps) {
+export function DsmMatrixView({ matrix, metrics, onSelectCell }: DsmMatrixViewProps) {
const [hover, setHover] = useState<{ row: number; col: number } | null>(null);
const counts = useMemo(() => {
@@ -56,6 +68,12 @@ export function DsmMatrixView({ matrix, onSelectCell }: DsmMatrixViewProps) {
return { present, violations, cycles };
}, [matrix]);
+ const rolesByNodeId = useMemo(() => {
+ const m = new Map<string, NodeRole>();
+ for (const r of metrics?.roles ?? []) m.set(r.id, r.role);
+ return m;
+ }, [metrics]);
+
if (matrix.axis.length === 0) {
return (
<EmptyState
@@ -85,6 +103,24 @@ export function DsmMatrixView({ matrix, onSelectCell }: DsmMatrixViewProps) {
<strong style={{ color: "var(--color-text-secondary)" }}>{counts.present}</strong>{" "}
dependencies
</span>
+ {metrics && (
+ <span title="Deterministic 1-10 architecture score (higher = lower coupling)">
+ score <strong style={{ color: "var(--color-text-secondary)" }}>{metrics.score.toFixed(1)}</strong>
+ </span>
+ )}
+ {metrics && (
+ <span title="Share of other services the average service can reach transitively">
+ propagation{" "}
+ <strong style={{ color: "var(--color-text-secondary)" }}>
+ {metrics.propagation_cost_pct.toFixed(1)}%
+ </strong>
+ </span>
+ )}
+ {metrics && metrics.core_size > 0 && (
+ <span style={{ color: "var(--color-warning)" }} title="Largest cyclic group of services">
+ core {metrics.core_size}
+ </span>
+ )}
{counts.violations > 0 && (
<span style={{ color: "var(--color-risk-high)" }}>{counts.violations} violation(s)</span>
)}
@@ -139,6 +175,8 @@ export function DsmMatrixView({ matrix, onSelectCell }: DsmMatrixViewProps) {
row={row}
label={matrix.labels[i] ?? ""}
axisId={matrix.axis[i] ?? ""}
+ axis={matrix.axis}
+ rolesByNodeId={rolesByNodeId}
hover={hover}
onHover={setHover}
{...(onSelectCell ? { onSelectCell } : {})}
@@ -155,6 +193,8 @@ function RowCells({
row,
label,
axisId,
+ axis,
+ rolesByNodeId,
hover,
onHover,
onSelectCell,
@@ -163,6 +203,8 @@ function RowCells({
row: DsmCell[];
label: string;
axisId: string;
+ axis: string[];
+ rolesByNodeId: ReadonlyMap<string, NodeRole>;
hover: { row: number; col: number } | null;
onHover: (h: { row: number; col: number } | null) => void;
onSelectCell?: (cell: DsmCell) => void;
@@ -191,12 +233,15 @@ function RowCells({
</div>
{row.map((cell, j) => {
const isDiagonal = i === j;
+ const role = isDiagonal ? rolesByNodeId.get(axis[j] ?? "") : undefined;
const interactive = cell.present && !isDiagonal && Boolean(onSelectCell);
- const title = cell.present
- ? `${cell.from_id} → ${cell.to_id} (${cell.kind ?? ""})${
- cell.violation ? " · violation" : cell.cycle ? " · cycle" : ""
- }`
- : undefined;
+ const title = isDiagonal && role
+ ? `${axisId} · ${roleStyle(role).label} — ${roleStyle(role).description}`
+ : cell.present
+ ? `${cell.from_id} → ${cell.to_id} (${cell.kind ?? ""})${
+ cell.violation ? " · violation" : cell.cycle ? " · cycle" : ""
+ }`
+ : undefined;
return (
<div
key={`cell-${i}-${j}`}
@@ -210,7 +255,7 @@ function RowCells({
height: CELL,
boxSizing: "border-box",
border: "1px solid var(--color-border-subtle)",
- background: cellBackground(cell, isDiagonal),
+ background: cellBackground(cell, isDiagonal, role),
boxShadow: cellRing(cell),
cursor: interactive ? "pointer" : "default",
outline:
diff --git a/packages/ui/src/workspace/system-map/architecture.ts b/packages/ui/src/workspace/system-map/architecture.ts
new file mode 100644
index 000000000..33928b2ed
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/architecture.ts
@@ -0,0 +1,71 @@
+/**
+ * Architecture-metrics overlay (Phase 6) — turns the workspace
+ * `ArchitectureMetrics` (computed by the core / REST layer) into a
+ * `SystemMapOverlay` the Live System Map renders without any component change,
+ * plus the shared role styling the DSM and the inspector reuse. The cyclic-core
+ * services are highlighted and badged "core" so the architectural center is
+ * obvious; the precise per-service role (Core / Shared / Control / Peripheral)
+ * shows in the inspector. Additive (no dimming): the map stays legible.
+ */
+
+import type { ArchitectureMetrics, NodeRole, SystemGraph } from "@repowise-dev/types";
+import type { SystemMapBadge, SystemMapOverlay } from "./types";
+
+export interface RoleStyle {
+ label: string;
+ /** A CSS color (variable) for tinting badges, diagonal cells, and dots. */
+ color: string;
+ /** One-line meaning, for legends and tooltips. */
+ description: string;
+}
+
+/** Canonical styling for each core-periphery role (the one place it lives). */
+export const ROLE_STYLE: Record<NodeRole, RoleStyle> = {
+ core: {
+ label: "Core",
+ color: "var(--color-warning)",
+ description: "In the largest cyclic group — the architectural center.",
+ },
+ shared: {
+ label: "Shared",
+ color: "var(--color-accent-secondary)",
+ description: "Many services depend on it; it depends on few (a utility).",
+ },
+ control: {
+ label: "Control",
+ color: "var(--color-accent-primary)",
+ description: "It depends on many; few depend on it (an orchestrator).",
+ },
+ peripheral: {
+ label: "Peripheral",
+ color: "var(--color-text-tertiary)",
+ description: "Lightly coupled in both directions.",
+ },
+};
+
+export const ROLE_ORDER: readonly NodeRole[] = ["core", "shared", "control", "peripheral"];
+
+export function roleStyle(role: NodeRole): RoleStyle {
+ return ROLE_STYLE[role] ?? ROLE_STYLE.peripheral;
+}
+
+/**
+ * Build the architecture overlay: highlight + badge the cyclic-core services.
+ * Returns an empty overlay when there is no core, so passing it through is
+ * always safe.
+ */
+export function buildArchitectureOverlay(
+ _graph: SystemGraph,
+ metrics: ArchitectureMetrics | null | undefined,
+): SystemMapOverlay {
+ if (!metrics || metrics.core_members.length === 0) return {};
+
+ const nodeBadges: Record<string, SystemMapBadge> = {};
+ const highlightNodeIds = new Set<string>();
+ for (const id of metrics.core_members) {
+ highlightNodeIds.add(id);
+ nodeBadges[id] = { label: "core", tone: "info" };
+ }
+
+ return { highlightNodeIds, nodeBadges };
+}
diff --git a/packages/ui/src/workspace/system-map/index.ts b/packages/ui/src/workspace/system-map/index.ts
index 7235d66c2..1fb33a2c7 100644
--- a/packages/ui/src/workspace/system-map/index.ts
+++ b/packages/ui/src/workspace/system-map/index.ts
@@ -20,6 +20,13 @@ export {
type SystemMapConformancePanelProps,
} from "./system-map-conformance-panel";
export { buildConformanceOverlay } from "./conformance";
+export {
+ buildArchitectureOverlay,
+ roleStyle,
+ ROLE_STYLE,
+ ROLE_ORDER,
+ type RoleStyle,
+} from "./architecture";
export { useSystemMapLayout, type SystemMapLayout, type UseSystemMapLayoutArgs } from "./use-system-map-layout";
export { applyView, computeSystemMapPositions, SYSTEM_MAP_NODE_SIZE, type SystemMapView } from "./layout";
export { collapseToRepos } from "./collapse";
diff --git a/packages/ui/src/workspace/system-map/system-map-inspector.tsx b/packages/ui/src/workspace/system-map/system-map-inspector.tsx
index d4f8c75c5..efb1c9f63 100644
--- a/packages/ui/src/workspace/system-map/system-map-inspector.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-inspector.tsx
@@ -9,8 +9,14 @@
*/
import { X } from "lucide-react";
-import type { SystemEdge, SystemGraph, SystemNode } from "@repowise-dev/types";
+import type {
+ NodeArchitectureRole,
+ SystemEdge,
+ SystemGraph,
+ SystemNode,
+} from "@repowise-dev/types";
import { HealthRing } from "../workspace-graph-node";
+import { roleStyle } from "./architecture";
import { edgeKindStyle, matchTypeLabel } from "./edge-kinds";
import { nodeKindStyle } from "./node-kinds";
import type { RepoHealth, SystemMapSelection } from "./types";
@@ -19,6 +25,8 @@ export interface SystemMapInspectorProps {
selection: SystemMapSelection;
graph: SystemGraph;
healthByRepo?: ReadonlyMap<string, RepoHealth>;
+ /** Per-service architecture role + visibility profile (Phase 6, optional). */
+ roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole>;
onClose: () => void;
/** Select another node (e.g. clicking a connected service). */
onSelectNode: (nodeId: string) => void;
@@ -76,11 +84,13 @@ function NodeBody({
node,
graph,
health,
+ role,
onSelectNode,
}: {
node: SystemNode;
graph: SystemGraph;
health: RepoHealth | null;
+ role: NodeArchitectureRole | null;
onSelectNode: (id: string) => void;
}) {
const kind = nodeKindStyle(node.kind);
@@ -98,6 +108,23 @@ function NodeBody({
</div>
</div>
<div>
+ {role && (
+ <Field
+ label="Role"
+ value={
+ <span title={roleStyle(role.role).description} style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
+ <span style={{ width: 7, height: 7, borderRadius: "50%", background: roleStyle(role.role).color }} />
+ {roleStyle(role.role).label}
+ </span>
+ }
+ />
+ )}
+ {role && (
+ <Field
+ label="Visibility (in / out)"
+ value={`${role.visibility_fan_in} / ${role.visibility_fan_out}`}
+ />
+ )}
{node.service_path && <Field label="Path" value={<span style={{ fontFamily: "var(--font-mono, monospace)", fontSize: 11 }}>{node.service_path}</span>} />}
<Field label="Provides" value={`${node.provider_count} contracts`} />
<Field label="Consumes" value={`${node.consumer_count} contracts`} />
@@ -223,7 +250,7 @@ function LinkText({ label, onClick }: { label: string; onClick: () => void }) {
);
}
-export function SystemMapInspector({ selection, graph, healthByRepo, onClose, onSelectNode, onOpenContract }: SystemMapInspectorProps) {
+export function SystemMapInspector({ selection, graph, healthByRepo, roleByNodeId, onClose, onSelectNode, onOpenContract }: SystemMapInspectorProps) {
if (!selection) return null;
if (selection.type === "node") {
@@ -232,7 +259,7 @@ export function SystemMapInspector({ selection, graph, healthByRepo, onClose, on
return (
<div style={panelStyle}>
<Header kind="Service" onClose={onClose} />
- <NodeBody node={node} graph={graph} health={healthByRepo?.get(node.repo) ?? null} onSelectNode={onSelectNode} />
+ <NodeBody node={node} graph={graph} health={healthByRepo?.get(node.repo) ?? null} role={roleByNodeId?.get(node.id) ?? null} onSelectNode={onSelectNode} />
</div>
);
}
diff --git a/packages/ui/src/workspace/system-map/system-map.tsx b/packages/ui/src/workspace/system-map/system-map.tsx
index 94c75651e..77b6c80fb 100644
--- a/packages/ui/src/workspace/system-map/system-map.tsx
+++ b/packages/ui/src/workspace/system-map/system-map.tsx
@@ -22,7 +22,7 @@ import {
type NodeMouseHandler,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
-import type { SystemEdgeKind, SystemGraph } from "@repowise-dev/types";
+import type { NodeArchitectureRole, SystemEdgeKind, SystemGraph } from "@repowise-dev/types";
import { EmptyState } from "../../shared/empty-state";
import { systemMapNodeTypes } from "./system-map-node";
import { systemMapEdgeTypes } from "./system-map-edge";
@@ -41,6 +41,8 @@ export interface SystemMapProps {
healthByRepo?: ReadonlyMap<string, RepoHealth>;
/** Additive decoration from a later phase (ripple, badges, violations). */
overlay?: SystemMapOverlay;
+ /** Per-service architecture role + visibility, shown in the inspector (optional). */
+ roleByNodeId?: ReadonlyMap<string, NodeArchitectureRole>;
/** Open a contract on the Contracts surface (edge drill-down). */
onOpenContract?: (contractId: string) => void;
}
@@ -53,7 +55,7 @@ export function SystemMap(props: SystemMapProps) {
);
}
-function SystemMapInner({ graph, loading, error, healthByRepo, overlay, onOpenContract }: SystemMapProps) {
+function SystemMapInner({ graph, loading, error, healthByRepo, overlay, roleByNodeId, onOpenContract }: SystemMapProps) {
const availableKinds = useMemo<Set<SystemEdgeKind>>(
() => new Set((graph?.edges ?? []).map((e) => e.kind)),
[graph],
@@ -179,6 +181,7 @@ function SystemMapInner({ graph, loading, error, healthByRepo, overlay, onOpenCo
selection={selection}
graph={graph}
{...(healthByRepo ? { healthByRepo } : {})}
+ {...(roleByNodeId ? { roleByNodeId } : {})}
onClose={() => setSelection(null)}
onSelectNode={selectNode}
{...(onOpenContract ? { onOpenContract } : {})}
diff --git a/packages/web/src/app/workspace/conformance/page.tsx b/packages/web/src/app/workspace/conformance/page.tsx
index 9d09d5a6c..f222b9f99 100644
--- a/packages/web/src/app/workspace/conformance/page.tsx
+++ b/packages/web/src/app/workspace/conformance/page.tsx
@@ -2,17 +2,22 @@
import { useMemo } from "react";
import { useRouter } from "next/navigation";
-import { ShieldCheck, ShieldAlert, RefreshCw, Waypoints, ListChecks } from "lucide-react";
+import { ShieldCheck, ShieldAlert, RefreshCw, Waypoints, ListChecks, Gauge } from "lucide-react";
import { buildDsm, DsmMatrixView } from "@repowise-dev/ui/workspace/dsm";
import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
import { StatCard } from "@repowise-dev/ui/shared/stat-card";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { useWorkspaceSystemGraph, useWorkspaceConformance } from "@/lib/hooks/use-workspace";
+import {
+ useWorkspaceSystemGraph,
+ useWorkspaceConformance,
+ useWorkspaceArchitecture,
+} from "@/lib/hooks/use-workspace";
export default function ConformancePage() {
const router = useRouter();
const { data: graph, isLoading: graphLoading } = useWorkspaceSystemGraph();
const { data: report, isLoading: reportLoading } = useWorkspaceConformance();
+ const { data: metrics } = useWorkspaceArchitecture();
const isLoading = graphLoading || reportLoading;
const matrix = useMemo(() => buildDsm(graph, report), [graph, report]);
@@ -39,7 +44,17 @@ export default function ConformancePage() {
</p>
</div>
- <div className="grid grid-cols-2 gap-3 lg:grid-cols-3">
+ <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
+ <StatCard
+ label="Architecture score"
+ value={metrics ? `${metrics.score.toFixed(1)} / 10` : "—"}
+ description={
+ metrics
+ ? `${metrics.architecture_type} · ${metrics.propagation_cost_pct.toFixed(1)}% propagation cost`
+ : "Coupling + core roll-up"
+ }
+ icon={<Gauge className="h-4 w-4 text-[var(--color-accent-primary)]" />}
+ />
<StatCard
label="Rules evaluated"
value={isLoading ? "—" : (report?.rules_evaluated ?? 0)}
@@ -82,7 +97,7 @@ export default function ConformancePage() {
{isLoading ? (
<Skeleton className="h-72 w-full" />
) : (
- <DsmMatrixView matrix={matrix} />
+ <DsmMatrixView matrix={matrix} {...(metrics ? { metrics } : {})} />
)}
</CardContent>
</Card>
diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsx
index 371636433..96bccff46 100644
--- a/packages/web/src/app/workspace/system-map/page.tsx
+++ b/packages/web/src/app/workspace/system-map/page.tsx
@@ -2,7 +2,7 @@
import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
-import { Waypoints, Boxes, ArrowLeftRight, Share2, Zap, AlertTriangle, ShieldAlert } from "lucide-react";
+import { Waypoints, Boxes, ArrowLeftRight, Share2, Zap, AlertTriangle, ShieldAlert, Gauge } from "lucide-react";
import {
SystemMap,
SystemMapBlastPanel,
@@ -11,8 +11,10 @@ import {
buildBlastRadiusOverlay,
buildBreakingChangeOverlay,
buildConformanceOverlay,
+ buildArchitectureOverlay,
type RepoHealth,
} from "@repowise-dev/ui/workspace/system-map";
+import type { NodeArchitectureRole } from "@/lib/api/types";
import { StatCard } from "@repowise-dev/ui/shared/stat-card";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
import {
@@ -21,6 +23,7 @@ import {
useWorkspaceBlastRadius,
useWorkspaceBreakingChanges,
useWorkspaceConformance,
+ useWorkspaceArchitecture,
} from "@/lib/hooks/use-workspace";
export default function SystemMapPage() {
@@ -49,6 +52,18 @@ export default function SystemMapPage() {
const { data: conformance, isLoading: conformanceLoading } =
useWorkspaceConformance(showConformance);
+ // Architecture metrics. Always fetched (cheap, deterministic): it feeds the
+ // score stat and the per-service role shown in the inspector. The cyclic-core
+ // highlight is an opt-in overlay toggle.
+ const { data: architecture } = useWorkspaceArchitecture();
+ const [showArchitecture, setShowArchitecture] = useState(false);
+
+ const roleByNodeId = useMemo<Map<string, NodeArchitectureRole>>(() => {
+ const m = new Map<string, NodeArchitectureRole>();
+ for (const r of architecture?.roles ?? []) m.set(r.id, r);
+ return m;
+ }, [architecture]);
+
// Join repo health (from the repo-level graph) onto service nodes by alias.
// The map keys health by `SystemNode.repo`; the repo graph's node `name` is
// the repo alias.
@@ -67,8 +82,9 @@ export default function SystemMapPage() {
if (blast) return buildBlastRadiusOverlay(graph, blast);
if (showConformance && conformance) return buildConformanceOverlay(graph, conformance);
if (showBreaking && breaking) return buildBreakingChangeOverlay(graph, breaking);
+ if (showArchitecture && architecture) return buildArchitectureOverlay(graph, architecture);
return undefined;
- }, [graph, blast, showBreaking, breaking, showConformance, conformance]);
+ }, [graph, blast, showBreaking, breaking, showConformance, conformance, showArchitecture, architecture]);
const diag = graph?.diagnostics;
const serviceCount = graph?.nodes.length ?? 0;
@@ -89,7 +105,17 @@ export default function SystemMapPage() {
</p>
</div>
- <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
+ <div className="grid grid-cols-2 gap-3 lg:grid-cols-5">
+ <StatCard
+ label="Architecture score"
+ value={architecture ? `${architecture.score.toFixed(1)} / 10` : "—"}
+ description={
+ architecture
+ ? `${architecture.propagation_cost_pct.toFixed(1)}% propagation cost`
+ : "Coupling + core roll-up"
+ }
+ icon={<Gauge className="h-4 w-4 text-[var(--color-accent-primary)]" />}
+ />
<StatCard
label="Services"
value={isLoading ? "—" : serviceCount}
@@ -144,14 +170,40 @@ export default function SystemMapPage() {
/>
Include co-change
</label>
+ <button
+ type="button"
+ onClick={() => {
+ setShowArchitecture((v) => !v);
+ if (!showArchitecture) {
+ setShowBreaking(false);
+ setShowConformance(false);
+ }
+ }}
+ aria-pressed={showArchitecture}
+ className={`ml-auto inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-sm ${
+ showArchitecture
+ ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"
+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
+ }`}
+ title="Highlight the cyclic architectural core"
+ >
+ <Gauge className="h-4 w-4" />
+ Core
+ {showArchitecture && architecture && architecture.core_size > 0 && (
+ <span className="font-semibold">· {architecture.core_size}</span>
+ )}
+ </button>
<button
type="button"
onClick={() => {
setShowConformance((v) => !v);
- if (!showConformance) setShowBreaking(false);
+ if (!showConformance) {
+ setShowBreaking(false);
+ setShowArchitecture(false);
+ }
}}
aria-pressed={showConformance}
- className={`ml-auto inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-sm ${
+ className={`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-sm ${
showConformance
? "border-[var(--color-risk-high)] text-[var(--color-risk-high)]"
: "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
@@ -167,7 +219,10 @@ export default function SystemMapPage() {
type="button"
onClick={() => {
setShowBreaking((v) => !v);
- if (!showBreaking) setShowConformance(false);
+ if (!showBreaking) {
+ setShowConformance(false);
+ setShowArchitecture(false);
+ }
}}
aria-pressed={showBreaking}
className={`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-sm ${
@@ -205,6 +260,7 @@ export default function SystemMapPage() {
error={error ?? null}
healthByRepo={healthByRepo}
{...(overlay ? { overlay } : {})}
+ roleByNodeId={roleByNodeId}
onOpenContract={() => router.push("/workspace/contracts")}
/>
<SystemMapBlastPanel
diff --git a/packages/web/src/lib/api/types/workspace.ts b/packages/web/src/lib/api/types/workspace.ts
index cae0a6fc0..efe138815 100644
--- a/packages/web/src/lib/api/types/workspace.ts
+++ b/packages/web/src/lib/api/types/workspace.ts
@@ -156,6 +156,10 @@ export type {
ConformanceReport,
DsmCell,
DsmMatrix,
+ ArchitectureMetrics,
+ NodeArchitectureRole,
+ NodeRole,
+ ArchitectureType,
} from "@repowise-dev/types";
import type {
@@ -163,6 +167,7 @@ import type {
CrossRepoBlastRadius,
BreakingChangeReport,
ConformanceReport,
+ ArchitectureMetrics,
} from "@repowise-dev/types";
/** `GET /api/workspace/system-graph` — the full service-granular system graph. */
@@ -176,3 +181,6 @@ export type WorkspaceBreakingChangesResponse = BreakingChangeReport;
/** `GET /api/workspace/conformance` — architecture rule violations + cycles. */
export type WorkspaceConformanceResponse = ConformanceReport;
+
+/** `GET /api/workspace/architecture` — architecture-complexity metrics + roles. */
+export type WorkspaceArchitectureResponse = ArchitectureMetrics;
diff --git a/packages/web/src/lib/api/workspace.ts b/packages/web/src/lib/api/workspace.ts
index b85a65a71..80e9e3780 100644
--- a/packages/web/src/lib/api/workspace.ts
+++ b/packages/web/src/lib/api/workspace.ts
@@ -9,6 +9,7 @@ import type {
WorkspaceBlastRadiusResponse,
WorkspaceBreakingChangesResponse,
WorkspaceConformanceResponse,
+ WorkspaceArchitectureResponse,
} from "./types";
export async function getWorkspace(
@@ -108,6 +109,10 @@ export async function getWorkspaceConformance(opts?: {
return apiGet<WorkspaceConformanceResponse>("/api/workspace/conformance", params);
}
+export async function getWorkspaceArchitecture(): Promise<WorkspaceArchitectureResponse> {
+ return apiGet<WorkspaceArchitectureResponse>("/api/workspace/architecture");
+}
+
/**
* Trigger a re-sync (re-index) of the workspace. Pass ``repoAlias`` to
* scope to one repo; otherwise the server fans out across every loaded
diff --git a/packages/web/src/lib/hooks/use-workspace.ts b/packages/web/src/lib/hooks/use-workspace.ts
index bbc46b8c3..3103d64ba 100644
--- a/packages/web/src/lib/hooks/use-workspace.ts
+++ b/packages/web/src/lib/hooks/use-workspace.ts
@@ -10,6 +10,7 @@ import {
getWorkspaceBlastRadius,
getWorkspaceBreakingChanges,
getWorkspaceConformance,
+ getWorkspaceArchitecture,
} from "@/lib/api/workspace";
import type {
WorkspaceResponse,
@@ -20,6 +21,7 @@ import type {
WorkspaceBlastRadiusResponse,
WorkspaceBreakingChangesResponse,
WorkspaceConformanceResponse,
+ WorkspaceArchitectureResponse,
} from "@/lib/api/types";
export function useWorkspace() {
@@ -123,6 +125,19 @@ export function useWorkspaceConformance(enabled = true) {
return { data: data ?? null, isLoading, error };
}
+/**
+ * Architecture-complexity metrics (propagation cost, core, 1-10 score, roles)
+ * computed from the system graph. Pass ``enabled=false`` to defer the request.
+ */
+export function useWorkspaceArchitecture(enabled = true) {
+ const { data, error, isLoading } = useSWR<WorkspaceArchitectureResponse>(
+ enabled ? "workspace:architecture" : null,
+ () => getWorkspaceArchitecture(),
+ { revalidateOnFocus: false },
+ );
+ return { data: data ?? null, isLoading, error };
+}
+
/** Repo-level graph (carries the per-repo health score used by the map). */
export function useWorkspaceGraph() {
const { data, error, isLoading } = useSWR<WorkspaceGraphResponse>(
diff --git a/tests/unit/workspace/test_architecture_metrics.py b/tests/unit/workspace/test_architecture_metrics.py
new file mode 100644
index 000000000..6999983a4
--- /dev/null
+++ b/tests/unit/workspace/test_architecture_metrics.py
@@ -0,0 +1,278 @@
+"""Tests for workspace architecture-complexity metrics.
+
+The numeric checks are hand-computed against the visibility matrix so the score
+formula and the propagation-cost normalization can't drift silently. The fixture
+shapes are the canonical complexity cases: a pure layered DAG, a fully cyclic
+graph, and a core-periphery system with one service in each role.
+"""
+
+from __future__ import annotations
+
+from repowise.core.workspace.architecture_metrics import (
+ ARCH_CORE_PERIPHERY,
+ ARCH_HIERARCHICAL,
+ ROLE_CONTROL,
+ ROLE_CORE,
+ ROLE_PERIPHERAL,
+ ROLE_SHARED,
+ SCORE_MAX,
+ architecture_score,
+ compute_architecture_metrics,
+)
+from repowise.core.workspace.system_graph import SystemEdge, SystemGraph, SystemNode
+
+# ---------------------------------------------------------------------------
+# Fixture builders (mirrors test_conformance.py)
+# ---------------------------------------------------------------------------
+
+
+def _node(node_id, repo=None, name=None, service_path=None) -> SystemNode:
+ return SystemNode(
+ id=node_id,
+ repo=repo or node_id.split("::", 1)[0],
+ service_path=service_path,
+ name=name or node_id,
+ )
+
+
+def _edge(source, target, kind="http", structural=True, match="exact") -> SystemEdge:
+ return SystemEdge(
+ id=f"{source}->{target}:{kind}",
+ source=source,
+ target=target,
+ kind=kind,
+ match_type=match,
+ confidence=1.0,
+ weight=1,
+ structural=structural,
+ )
+
+
+def _graph(nodes, edges) -> SystemGraph:
+ return SystemGraph(nodes=[_node(n) for n in nodes], edges=edges)
+
+
+def _roles_by_id(metrics):
+ return {r.id: r for r in metrics.roles}
+
+
+# ---------------------------------------------------------------------------
+# Pure layered DAG: A -> B -> C
+# ---------------------------------------------------------------------------
+
+
+def test_layered_dag_low_coupling_high_score():
+ graph = _graph(["A", "B", "C"], [_edge("A", "B"), _edge("B", "C")])
+ m = compute_architecture_metrics(graph)
+
+ # Visibility (incl self): A->{A,B,C}=3, B->{B,C}=2, C->{C}=1. Total 6.
+ # Off-diagonal = 6 - 3 = 3; denominator = 3*2 = 6; pc = 0.5.
+ assert m.propagation_cost == 0.5
+ assert m.propagation_cost_pct == 50.0
+ # No cyclic group.
+ assert m.core_size == 0
+ assert m.core_members == []
+ assert m.cycle_count == 0
+ assert m.architecture_type == ARCH_HIERARCHICAL
+ # score = 10 - 5*0.5 - 0 - 0 - 0 = 7.5
+ assert m.score == 7.5
+
+ roles = _roles_by_id(m)
+ # A reaches B,C but nothing reaches A -> high fan-out, low fan-in -> control.
+ assert roles["A"].role == ROLE_CONTROL
+ # C is reached by A,B but reaches nothing else -> shared.
+ assert roles["C"].role == ROLE_SHARED
+
+
+# ---------------------------------------------------------------------------
+# Fully cyclic: A -> B -> C -> A
+# ---------------------------------------------------------------------------
+
+
+def test_fully_cyclic_high_coupling_low_score():
+ graph = _graph(
+ ["A", "B", "C"],
+ [_edge("A", "B"), _edge("B", "C"), _edge("C", "A")],
+ )
+ m = compute_architecture_metrics(graph)
+
+ # Everything reaches everything: pc = 1.0.
+ assert m.propagation_cost == 1.0
+ assert m.core_size == 3
+ assert m.core_members == ["A", "B", "C"]
+ assert m.core_ratio == 1.0
+ assert m.cycle_count == 1
+ assert m.architecture_type == ARCH_CORE_PERIPHERY
+ # score = 10 - 5*1.0 - 3*1.0 - min(2, 0.5*1) = 1.5
+ assert m.score == 1.5
+ assert all(r.role == ROLE_CORE for r in m.roles)
+
+
+def test_cyclic_scores_below_layered():
+ dag = compute_architecture_metrics(_graph(["A", "B", "C"], [_edge("A", "B"), _edge("B", "C")]))
+ cyclic = compute_architecture_metrics(
+ _graph(["A", "B", "C"], [_edge("A", "B"), _edge("B", "C"), _edge("C", "A")])
+ )
+ assert cyclic.score < dag.score
+
+
+# ---------------------------------------------------------------------------
+# Core-periphery: cyclic core {A,B,C} + shared lib L + control gateway G +
+# peripheral leaf P. One service in each role.
+# ---------------------------------------------------------------------------
+
+
+def _core_periphery_graph() -> SystemGraph:
+ return _graph(
+ ["A", "B", "C", "L", "G", "P"],
+ [
+ _edge("A", "B"),
+ _edge("B", "C"),
+ _edge("C", "A"), # cyclic core
+ _edge("A", "L"), # core depends on shared lib
+ _edge("G", "A"), # gateway calls into the core
+ _edge("G", "P"), # gateway calls a peripheral leaf
+ ],
+ )
+
+
+def test_core_periphery_roles_and_type():
+ m = compute_architecture_metrics(_core_periphery_graph())
+
+ assert m.core_members == ["A", "B", "C"]
+ assert m.core_size == 3
+ assert m.architecture_type == ARCH_CORE_PERIPHERY
+
+ roles = _roles_by_id(m)
+ assert roles["A"].role == ROLE_CORE
+ assert roles["B"].role == ROLE_CORE
+ assert roles["C"].role == ROLE_CORE
+ # L: reached by the whole core + gateway, depends on nothing -> shared.
+ assert roles["L"].role == ROLE_SHARED
+ # G: reaches the whole system, nothing reaches it -> control.
+ assert roles["G"].role == ROLE_CONTROL
+ # P: only the gateway reaches it, it reaches nothing -> peripheral.
+ assert roles["P"].role == ROLE_PERIPHERAL
+
+ assert m.role_breakdown() == {
+ ROLE_CORE: 3,
+ ROLE_SHARED: 1,
+ ROLE_CONTROL: 1,
+ ROLE_PERIPHERAL: 1,
+ }
+
+
+def test_core_periphery_propagation_cost_by_hand():
+ m = compute_architecture_metrics(_core_periphery_graph())
+ # Visibility incl self:
+ # A->{A,B,C,L}=4, B->{B,C,A,L}=4, C->{C,A,B,L}=4,
+ # L->{L}=1, G->{G,A,B,C,L,P}=6, P->{P}=1. Total = 20.
+ # Off-diagonal = 20 - 6 = 14; denominator = 6*5 = 30; pc = 14/30 = 0.4667.
+ assert m.propagation_cost == round(14 / 30, 4)
+
+
+# ---------------------------------------------------------------------------
+# Structural-only guard: a co-change edge must not move any metric.
+# ---------------------------------------------------------------------------
+
+
+def test_cochange_edge_does_not_affect_metrics():
+ base = _graph(["A", "B", "C"], [_edge("A", "B"), _edge("B", "C")])
+ with_cochange = _graph(
+ ["A", "B", "C"],
+ [
+ _edge("A", "B"),
+ _edge("B", "C"),
+ _edge("C", "A", kind="co_change", structural=False, match="inferred"),
+ ],
+ )
+ a = compute_architecture_metrics(base)
+ b = compute_architecture_metrics(with_cochange)
+ assert a.to_dict() == b.to_dict()
+ # The behavioral edge does not create a cyclic core.
+ assert b.core_size == 0
+
+
+# ---------------------------------------------------------------------------
+# Determinism / snapshot: lock the shape and a known score.
+# ---------------------------------------------------------------------------
+
+
+def test_snapshot_shape_and_score_are_locked():
+ m = compute_architecture_metrics(_core_periphery_graph(), generated_at="t0")
+ payload = m.to_dict()
+
+ assert set(payload.keys()) == {
+ "node_count",
+ "structural_edge_count",
+ "propagation_cost",
+ "propagation_cost_pct",
+ "core_size",
+ "core_ratio",
+ "core_members",
+ "cycle_count",
+ "conformance_violations",
+ "architecture_type",
+ "score",
+ "role_breakdown",
+ "roles",
+ "generated_at",
+ }
+ # score = 10 - 5*(14/30) - 3*(3/6) - min(2, 0.5*1) - 0
+ # = 10 - 2.3333 - 1.5 - 0.5 = 5.6667 -> 5.7
+ assert payload["score"] == 5.7
+ assert payload["node_count"] == 6
+ assert payload["structural_edge_count"] == 6
+ assert payload["generated_at"] == "t0"
+ assert payload["roles"][0].keys() >= {"id", "visibility_fan_in", "role"}
+
+
+def test_conformance_violations_lower_the_score():
+ graph = _graph(["A", "B", "C"], [_edge("A", "B"), _edge("B", "C")])
+ clean = compute_architecture_metrics(graph)
+ flagged = compute_architecture_metrics(graph, conformance_violations=3)
+ # 3 violations -> min(2, 0.5*3) = 1.5 point penalty.
+ assert flagged.score == round(clean.score - 1.5, 1)
+ assert flagged.conformance_violations == 3
+
+
+# ---------------------------------------------------------------------------
+# Degenerate workspaces.
+# ---------------------------------------------------------------------------
+
+
+def test_empty_workspace():
+ m = compute_architecture_metrics(SystemGraph(nodes=[], edges=[]))
+ assert m.node_count == 0
+ assert m.propagation_cost == 0.0
+ assert m.core_size == 0
+ assert m.score == SCORE_MAX
+ assert m.architecture_type == ARCH_HIERARCHICAL
+ assert m.roles == []
+
+
+def test_single_service_is_decoupled():
+ m = compute_architecture_metrics(_graph(["solo"], []))
+ assert m.node_count == 1
+ assert m.propagation_cost == 0.0
+ assert m.core_size == 0
+ assert m.score == SCORE_MAX
+ roles = _roles_by_id(m)
+ assert roles["solo"].role == ROLE_PERIPHERAL
+
+
+def test_independent_services_are_fully_decoupled():
+ m = compute_architecture_metrics(_graph(["A", "B", "C"], []))
+ assert m.propagation_cost == 0.0
+ assert m.score == SCORE_MAX
+ assert all(r.role == ROLE_PERIPHERAL for r in m.roles)
+
+
+# ---------------------------------------------------------------------------
+# Score helper bounds.
+# ---------------------------------------------------------------------------
+
+
+def test_score_is_clamped_to_range():
+ assert architecture_score(1.0, 1.0, 100, 100) >= 1.0
+ assert architecture_score(0.0, 0.0, 0, 0) == SCORE_MAX