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 conformance, dependency cycles, and DSM view (#515)

Raghav Chamadiyacd5d4a1a893b
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md
index 1a6bc416e..13f8c4281 100644
--- a/docs/CLI_REFERENCE.md
+++ b/docs/CLI_REFERENCE.md
@@ -550,6 +550,15 @@ repowise workspace diagnostics --json # raw JSON
repowise workspace diagnostics --repo api # limit to one repo alias
```
+### `repowise workspace check`
+
+Architecture lint: check the declared `conformance:` rules against the system graph and detect dependency cycles. Exits non-zero on any finding, so it gates CI.
+
+```bash
+repowise workspace check # human-readable report; exit 1 on findings
+repowise workspace check --json # raw report JSON
+```
+
See [Workspaces](WORKSPACES.md) for the full multi-repo guide.
---
diff --git a/docs/CONFIG.md b/docs/CONFIG.md
index d99e985aa..fd6658aaf 100644
--- a/docs/CONFIG.md
+++ b/docs/CONFIG.md
@@ -270,3 +270,49 @@ repowise init
```
The schema is managed with Alembic migrations.
+
+---
+
+## Workspace config (`.repowise-workspace.yaml`)
+
+A multi-repo [workspace](WORKSPACES.md) is configured by a `.repowise-workspace.yaml` at the workspace root. Alongside the repo list it carries two optional blocks.
+
+### `repos[].tags`
+
+Each repo entry may declare free-form `tags` used to group services in conformance rules:
+
+```yaml
+repos:
+ - path: web
+ alias: frontend
+ tags: [ui, edge]
+ - path: services/db
+ alias: db
+ tags: [data]
+```
+
+### The `conformance:` block
+
+Declares architecture conformance rules (allow/deny dependency rules) checked by `repowise workspace check` and the workspace Conformance view. See [Architecture Conformance](WORKSPACES.md#architecture-conformance).
+
+```yaml
+conformance:
+ rules:
+ - source: frontend # matcher: a glob over node id / repo / name
+ target: db # matcher
+ allow: false # optional, default false (deny). true = exception
+ description: "..." # optional, shown in reports
+ - source: "tag:ui" # matcher: tag:<name> — repos carrying that tag
+ target: "tag:data"
+ - source: "*" # matcher: * — any service
+ target: legacy-payments
+```
+
+| Field | Type | Default | Meaning |
+|-------|------|---------|---------|
+| `source` | string (matcher) | required | The dependent side. `*`, `tag:<name>`, or a glob over node id / repo alias / display name |
+| `target` | string (matcher) | required | The depended-upon side (same matcher forms) |
+| `allow` | bool | `false` | `false` = deny (a matching dependency is a violation); `true` = whitelist an otherwise-denied edge |
+| `description` | string | `""` | Human-readable rationale, surfaced in reports |
+
+Rules are evaluated only against structural edges (HTTP, gRPC, event, package, db); behavioral co-change is never treated as a dependency.
diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md
index 7c5c1d6f3..252692ace 100644
--- a/docs/MCP_TOOLS.md
+++ b/docs/MCP_TOOLS.md
@@ -28,6 +28,7 @@ repowise mcp --transport sse --port 7338 # legacy SSE transport
| `get_dead_code` | Unreachable code | Cleanup tasks |
| `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 |
---
@@ -217,6 +218,8 @@ When `changed_files` is passed, the response leads with a `directive` block. In
- `will_break_consumers` — services in *other* repos that depend on this one (structural impact), each with `repo`, `service`, `distance`, `score`, and the edge kinds carrying the impact.
- `missing_cross_repo_cochanges` — services in other repos that historically co-change with this one but aren't in the diff.
- `breaking_changes` — provider contracts in this repo that changed *incompatibly* since the last index (a removed route or field, a type or field-number change, a newly-required field), each with the changed `contract_id`, the change `kind`/`severity`, and the `impacted_consumers` (repo, service, file) it endangers across repos. Schema-level truth, distinct from the topology-level `will_break_consumers`; non-breaking changes (added optional field, new endpoint) never appear. See [Breaking-Change Guard](WORKSPACES.md#breaking-change-guard).
+- `conformance_violations` — declared dependency-rule breaches the diff's repo participates in, each with the offending `source`/`target` services, the `rule` (e.g. `frontend !-> db`), and `edge_kind`. See [Architecture Conformance](WORKSPACES.md#architecture-conformance).
+- `dependency_cycles` — circular service dependencies involving this repo, each with the participating `nodes` and `length`.
**When to use:** Before modifying files — especially hotspots. Understand what could break, who to involve in review, and whether tests cover the affected area.
@@ -254,6 +257,29 @@ get_blast_radius(targets=["mono::services/auth"], max_depth=2, include_behaviora
---
+## `get_conformance`
+
+*(Workspace mode only.)* Architecture governance: does the live system graph obey the declared dependency rules, and are there circular service dependencies?
+
+**Parameters:**
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `repo` | string | No | Limit findings to those involving this repo alias |
+
+**Returns:** `violations` (each with the offending `source`/`target` services, the `rule_source`/`rule_target` matchers that fired, and the `edge_kind`), `cycles` (each with the participating `nodes` and `length`), and the `violation_count` / `cycle_count` / `rules_evaluated` rollups.
+
+**When to use:** Before a refactor that changes service boundaries, or to audit whether the live architecture still matches the intended one. Rules are declared under `conformance:` in `.repowise-workspace.yaml`. See [Architecture Conformance](WORKSPACES.md#architecture-conformance).
+
+**Example calls:**
+
+```
+get_conformance()
+get_conformance(repo="frontend")
+```
+
+---
+
## `get_why`
Architectural decision intelligence. Three modes depending on parameters.
@@ -357,6 +383,7 @@ The MCP server automatically enriches responses with cross-repo intelligence:
- **Package dependencies** between repos
- **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
---
diff --git a/docs/WORKSPACES.md b/docs/WORKSPACES.md
index 5fb35ee0f..db7c2f1be 100644
--- a/docs/WORKSPACES.md
+++ b/docs/WORKSPACES.md
@@ -179,6 +179,15 @@ repowise workspace diagnostics --json # raw JSON
repowise workspace diagnostics --repo api # limit to one repo
```
+### `repowise workspace check`
+
+Architecture lint: check the declared `conformance:` rules against the system graph and detect dependency cycles. Exits non-zero on any finding, so it gates CI. See [Architecture Conformance](#architecture-conformance).
+
+```bash
+repowise workspace check # human-readable report; exit 1 on findings
+repowise workspace check --json # raw report JSON
+```
+
---
## Cross-Repo Intelligence
@@ -329,12 +338,76 @@ Use it three ways:
---
+## Architecture Conformance
+
+Workspaces let you declare, in `.repowise-workspace.yaml`, which services are *allowed* to depend on which others, and then continuously check the live system graph against those rules. This is your team's **architecture lint**: the intended architecture, expressed as code, verified on every update.
+
+### Declaring rules
+
+Conformance rules live in a `conformance:` block in the workspace config (no separate file). Each rule has a `source` and a `target` *matcher* and an `allow` flag:
+
+```yaml
+repos:
+ - path: web
+ alias: frontend
+ tags: [ui, edge]
+ - path: services/db
+ alias: db
+ tags: [data]
+
+conformance:
+ rules:
+ # Deny rules (allow defaults to false): the dependency is a violation.
+ - source: frontend
+ target: db
+ description: The UI must call the API, never the database directly.
+ - source: "*"
+ target: legacy-payments
+ # Tag-based: nothing in the "ui" tier may depend on the "data" tier...
+ - source: "tag:ui"
+ target: "tag:data"
+ # ...except migrations, which are explicitly allowed (an exception).
+ - source: migrations
+ target: db
+ allow: true
+```
+
+A **matcher** resolves against service nodes in the [system graph](#system-graph):
+
+| Matcher form | Matches |
+|--------------|---------|
+| `*` | every service |
+| `tag:<name>` | every service whose repo declares that tag (see `tags:` on each repo) |
+| anything else | a glob over the node id, repo alias, and display name (`frontend`, `api::*`, `*-worker`) |
+
+A rule with `allow: false` (the default) is a **deny** rule: a structural dependency from a matching source to a matching target is a violation. A rule with `allow: true` is an **exception** that whitelists an otherwise-denied edge. Only structural edges (HTTP, gRPC, event, package, db) are evaluated; behavioral co-change is never a dependency.
+
+### Dependency cycles
+
+Independently of any rules, conformance detects **circular dependencies** among services over structural edges (`A → B → … → A`). A cycle means the services cannot be built, deployed, or reasoned about independently. Cycle detection runs even with zero rules declared, so every workspace gets it for free.
+
+### Using it
+
+- **CLI** — `repowise workspace check` prints violations and cycles and exits non-zero when any are found, so it gates CI (the architecture lint):
+
+ ```bash
+ repowise workspace check # human-readable report; exit 1 on findings
+ repowise workspace check --json # raw report JSON (still exits 1 on findings)
+ ```
+
+ It recomputes from the persisted system graph, so editing rules and re-running picks them up without a full re-index.
+- **REST** — `GET /api/workspace/conformance` returns the report from the most recent update (filterable by `repo`).
+- **MCP** — `get_conformance` exposes violations and cycles to an agent; the `get_risk` PR-mode directive gains `conformance_violations` and `dependency_cycles` blocks for the findings the diff's repo participates in.
+- **Conformance view** — the web UI's Conformance page renders a **dependency-structure matrix (DSM)**: services on both axes, each filled cell a dependency tinted by transport, with rule violations ringed red and cycle cells amber. Governance panels list the violations and cycles. Violations also badge the offending edges on the [Live System Map](#live-system-map) (toggle **Conformance**), reusing the same additive overlay as the breaking-change guard.
+
+---
+
## 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))
+- **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))
- **Repo parameter** — most tools accept an optional `repo` parameter to target a specific repo, or `"all"` to query across the workspace
---
@@ -351,6 +424,7 @@ my-workspace/
contracts.json # Extracted API contracts and links
system_graph.json # Service-granular system graph + diagnostics
breaking_changes.json # Breaking provider changes vs the last index
+ conformance.json # Architecture rule violations + dependency cycles
.claude/
CLAUDE.md # Workspace-level CLAUDE.md for AI editors
backend/
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
index 9b4dde58d..e725931ec 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
@@ -991,3 +991,96 @@ def workspace_diagnostics(path: str | None, repo_alias: str | None, as_json: boo
console.print(
"\n [green]✓[/green] Every consumer matched a provider; no orphan providers."
)
+
+
+# ---------------------------------------------------------------------------
+# workspace check
+# ---------------------------------------------------------------------------
+
+
+@workspace_group.command("check")
[email protected]("path", required=False, default=None)
[email protected]("--json", "as_json", is_flag=True, help="Emit the raw conformance report as JSON.")
+def workspace_check(path: str | None, as_json: bool) -> None:
+ """Architecture lint — fail on dependency-rule violations or cycles.
+
+ Checks the declared ``conformance`` rules in ``.repowise-workspace.yaml``
+ against the system graph and detects circular service dependencies. Exits
+ non-zero when any violation or cycle is found, so it can gate CI. Reads (and
+ recomputes from) the system graph built by 'repowise update --workspace', so
+ editing rules and re-running picks them up without a full re-index.
+ """
+ import json as _json
+ import sys
+
+ from repowise.core.workspace.conformance import (
+ build_conformance_report,
+ 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."
+ )
+
+ report = build_conformance_report(
+ graph,
+ ws_config.conformance.rules,
+ tags_by_repo_from_config(ws_config),
+ )
+
+ if as_json:
+ console.print_json(_json.dumps(report.to_dict()))
+ if report.has_findings:
+ sys.exit(1)
+ return
+
+ rule_count = report.rules_evaluated
+ if rule_count == 0:
+ console.print(
+ "[dim]No conformance rules declared.[/dim] Add a [bold]conformance:[/bold] "
+ "block to .repowise-workspace.yaml to enforce allowed dependencies."
+ )
+
+ # Rule violations
+ if report.violations:
+ 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(
+ f" [red]{v.source}[/red] -> [red]{v.target}[/red] "
+ f"([dim]{v.edge_kind}[/dim]) violates [yellow]{rule}[/yellow]"
+ )
+ if v.rule_description:
+ console.print(f" [dim]{v.rule_description}[/dim]")
+
+ # Dependency cycles
+ if report.cycles:
+ console.print(f"\n[red]✗ {len(report.cycles)} dependency cycle(s):[/red]")
+ for c in report.cycles:
+ loop = " -> ".join([*c.nodes, c.nodes[0]]) if c.nodes else ""
+ console.print(f" [red]{loop}[/red]")
+
+ if not report.has_findings:
+ if rule_count:
+ console.print(
+ f"\n[green]✓[/green] No violations of {rule_count} rule(s); "
+ "no dependency cycles."
+ )
+ else:
+ console.print("\n[green]✓[/green] No dependency cycles.")
+ return
+
+ console.print(
+ f"\n[red]Architecture check failed:[/red] {len(report.violations)} violation(s), "
+ f"{len(report.cycles)} cycle(s)."
+ )
+ sys.exit(1)
diff --git a/packages/core/src/repowise/core/workspace/config.py b/packages/core/src/repowise/core/workspace/config.py
index c01c61d50..dfbe969b0 100644
--- a/packages/core/src/repowise/core/workspace/config.py
+++ b/packages/core/src/repowise/core/workspace/config.py
@@ -35,6 +35,10 @@ class RepoEntry:
is_primary: bool = False
indexed_at: str | None = None # ISO 8601 timestamp of last index
last_commit_at_index: str | None = None # Git SHA at last index
+ # Free-form labels (e.g. "frontend", "tier:edge", "legacy") that group repos
+ # for architecture conformance rules. A rule like ``frontend !-> db`` matches
+ # by tag via ``tag:<name>``; every service node in this repo inherits these.
+ tags: list[str] = field(default_factory=list)
def to_dict(self) -> dict[str, Any]:
d: dict[str, Any] = {"path": self.path, "alias": self.alias}
@@ -44,6 +48,8 @@ class RepoEntry:
d["indexed_at"] = self.indexed_at
if self.last_commit_at_index is not None:
d["last_commit_at_index"] = self.last_commit_at_index
+ if self.tags:
+ d["tags"] = list(self.tags)
return d
@classmethod
@@ -56,6 +62,7 @@ class RepoEntry:
is_primary=bool(data.get("is_primary", False)),
indexed_at=data.get("indexed_at"),
last_commit_at_index=data.get("last_commit_at_index"),
+ tags=[str(t) for t in data.get("tags", [])],
)
@@ -110,10 +117,7 @@ class ContractConfig:
@classmethod
def from_dict(cls, data: dict[str, Any]) -> ContractConfig:
- manual = [
- ManualContractLink.from_dict(ml)
- for ml in data.get("manual_links", [])
- ]
+ manual = [ManualContractLink.from_dict(ml) for ml in data.get("manual_links", [])]
return cls(
detect_http=bool(data.get("detect_http", True)),
detect_grpc=bool(data.get("detect_grpc", True)),
@@ -122,6 +126,66 @@ class ContractConfig:
)
+@dataclass
+class ConformanceRule:
+ """One architecture conformance rule: a dependency *source* may or may not
+ depend on a *target*.
+
+ ``source`` and ``target`` are **matchers** resolved against system-graph
+ service nodes (see :mod:`repowise.core.workspace.conformance`):
+
+ * ``"*"`` — any service
+ * ``"tag:<name>"`` — every service whose repo carries that tag
+ * any other string — a glob matched against the node id, repo alias, and
+ display name (so ``"frontend"`` matches a repo and ``"api::*"`` a service)
+
+ ``allow=False`` (the default) is a *deny* rule: a structural dependency from
+ a matching source to a matching target is a violation. ``allow=True`` is an
+ *exception* that whitelists an otherwise-denied edge (e.g. deny ``* !-> db``
+ but allow ``migrations -> db``).
+ """
+
+ source: str
+ target: str
+ allow: bool = False
+ description: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ d: dict[str, Any] = {"source": self.source, "target": self.target}
+ if self.allow:
+ d["allow"] = True
+ if self.description:
+ d["description"] = self.description
+ return d
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> ConformanceRule:
+ if "source" not in data or "target" not in data:
+ raise ValueError(
+ f"ConformanceRule requires 'source' and 'target', got: {sorted(data.keys())}"
+ )
+ return cls(
+ source=str(data["source"]),
+ target=str(data["target"]),
+ allow=bool(data.get("allow", False)),
+ description=str(data.get("description", "")),
+ )
+
+
+@dataclass
+class ConformanceConfig:
+ """Architecture conformance rules for the workspace (Phase 5)."""
+
+ rules: list[ConformanceRule] = field(default_factory=list)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {"rules": [r.to_dict() for r in self.rules]}
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> ConformanceConfig:
+ return cls(rules=[ConformanceRule.from_dict(r) for r in data.get("rules", [])])
+
+
@dataclass
class WorkspaceConfig:
"""Workspace-level configuration stored in ``.repowise-workspace.yaml``."""
@@ -130,6 +194,7 @@ class WorkspaceConfig:
repos: list[RepoEntry] = field(default_factory=list)
default_repo: str | None = None
contracts: ContractConfig = field(default_factory=ContractConfig)
+ conformance: ConformanceConfig = field(default_factory=ConformanceConfig)
# ------------------------------------------------------------------
# Serialization
@@ -144,12 +209,17 @@ class WorkspaceConfig:
}
# Only include contracts section if non-default
contracts_d = self.contracts.to_dict()
- if self.contracts.manual_links or not all([
- self.contracts.detect_http,
- self.contracts.detect_grpc,
- self.contracts.detect_topics,
- ]):
+ if self.contracts.manual_links or not all(
+ [
+ self.contracts.detect_http,
+ self.contracts.detect_grpc,
+ self.contracts.detect_topics,
+ ]
+ ):
d["contracts"] = contracts_d
+ # Only include conformance section when rules are declared.
+ if self.conformance.rules:
+ d["conformance"] = self.conformance.to_dict()
return d
@classmethod
@@ -163,12 +233,14 @@ class WorkspaceConfig:
repos.append(RepoEntry.from_dict(entry))
contracts = ContractConfig.from_dict(data.get("contracts", {}))
+ conformance = ConformanceConfig.from_dict(data.get("conformance", {}))
return cls(
version=version,
repos=repos,
default_repo=str(default_repo) if default_repo else None,
contracts=contracts,
+ conformance=conformance,
)
def save(self, workspace_root: Path) -> Path:
diff --git a/packages/core/src/repowise/core/workspace/conformance.py b/packages/core/src/repowise/core/workspace/conformance.py
new file mode 100644
index 000000000..717540029
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/conformance.py
@@ -0,0 +1,393 @@
+"""Architecture conformance — check declared dependency rules + find cycles.
+
+A team declares, in ``.repowise-workspace.yaml``, which services are *allowed* to
+depend on which others (``frontend !-> db``, ``* !-> legacy-payments``). This
+module checks those rules against the structural edges of the system graph and
+reports every violating dependency, and — together with
+:mod:`repowise.core.workspace.cycles` — assembles the workspace's architecture
+governance report (violations + dependency cycles).
+
+**Rule vocabulary.** A rule's ``source`` / ``target`` are *matchers* resolved
+against service nodes by a small registry (the D10 / PR #505 plugin shape — a new
+matcher form is a decorated resolver, never an ``if/elif``):
+
+* ``"*"`` — any service.
+* ``"tag:<name>"`` — every service whose repo carries that tag (tags are declared
+ on each ``RepoEntry`` and inherited by its service nodes).
+* any other string — a glob matched against the node id, repo alias, and display
+ name, so ``"frontend"`` matches a repo and ``"api::*"`` a specific service.
+
+A rule with ``allow=False`` (the default) is a *deny* rule: a structural
+dependency from a matching source to a matching target is a violation. A rule
+with ``allow=True`` is an *exception* that whitelists an otherwise-denied edge
+(deny ``* !-> db`` but allow ``migrations -> db``).
+
+**Structural edges only.** Conformance is about real dependencies; behavioral
+co-change edges are never evaluated.
+
+Pure and I/O-free except the thin ``save`` / ``load`` helpers and the
+``run_conformance_check`` orchestrator at the bottom.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from fnmatch import fnmatchcase
+from pathlib import Path
+from typing import Any
+
+from repowise.core.workspace.config import (
+ WORKSPACE_DATA_DIR,
+ ConformanceRule,
+ WorkspaceConfig,
+ ensure_workspace_data_dir,
+)
+from repowise.core.workspace.cycles import DependencyCycle, detect_cycles
+from repowise.core.workspace.system_graph import SystemGraph, SystemNode
+
+_log = logging.getLogger("repowise.workspace.conformance")
+
+# ---------------------------------------------------------------------------
+# Constants (single source of truth)
+# ---------------------------------------------------------------------------
+
+CONFORMANCE_FILENAME = "conformance.json"
+
+#: A rule violation always reads as an error; cycles read as a warning by default
+#: (a cycle is a smell, a denied dependency is an explicit policy breach).
+SEVERITY_VIOLATION = "violation"
+
+
+# ---------------------------------------------------------------------------
+# Matcher resolver registry (plugin shape — add a form = add a resolver)
+# ---------------------------------------------------------------------------
+
+#: A compiled matcher: does this node match, given the repo→tags map?
+MatcherPredicate = Callable[[SystemNode, dict[str, list[str]]], bool]
+
+#: A resolver inspects a raw matcher string and returns a predicate if it owns
+#: that form, else ``None`` so the next resolver gets a turn.
+MatcherResolver = Callable[[str], "MatcherPredicate | None"]
+
+_MATCHER_RESOLVERS: list[MatcherResolver] = []
+
+
+def matcher_resolver(fn: MatcherResolver) -> MatcherResolver:
+ """Register a matcher-string resolver. First to claim a form wins."""
+ _MATCHER_RESOLVERS.append(fn)
+ return fn
+
+
+@matcher_resolver
+def _wildcard_matcher(raw: str) -> MatcherPredicate | None:
+ """``"*"`` matches every service."""
+ if raw.strip() == "*":
+ return lambda node, tags_by_repo: True
+ return None
+
+
+@matcher_resolver
+def _tag_matcher(raw: str) -> MatcherPredicate | None:
+ """``"tag:<name>"`` matches services whose repo carries that tag."""
+ prefix = "tag:"
+ if not raw.startswith(prefix):
+ return None
+ tag = raw[len(prefix) :].strip()
+
+ def _match(node: SystemNode, tags_by_repo: dict[str, list[str]]) -> bool:
+ return tag in tags_by_repo.get(node.repo, [])
+
+ return _match
+
+
+@matcher_resolver
+def _glob_matcher(raw: str) -> MatcherPredicate | None:
+ """Fallback: glob the node id, repo alias, and display name.
+
+ Always claims the string, so it must stay registered last. A bare alias
+ (``"frontend"``) matches the repo and its nodes; a pattern (``"api::*"``)
+ targets a specific service.
+ """
+ pattern = raw.strip()
+
+ def _match(node: SystemNode, tags_by_repo: dict[str, list[str]]) -> bool:
+ return (
+ fnmatchcase(node.id, pattern)
+ or fnmatchcase(node.repo, pattern)
+ or fnmatchcase(node.name, pattern)
+ )
+
+ return _match
+
+
+def compile_matcher(raw: str) -> MatcherPredicate:
+ """Compile a matcher string to a predicate via the resolver registry."""
+ for resolver in _MATCHER_RESOLVERS:
+ predicate = resolver(raw)
+ if predicate is not None:
+ return predicate
+ # Unreachable while the glob fallback is registered; defensive only.
+ raise ValueError(f"No matcher resolver claimed: {raw!r}")
+
+
+# ---------------------------------------------------------------------------
+# Data models
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class ConformanceViolation:
+ """A structural dependency that a deny rule forbids."""
+
+ rule_source: str # the rule's source matcher
+ rule_target: str # the rule's target matcher
+ rule_description: str
+ source: str # offending node id (depends on target)
+ source_name: str
+ target: str # node id depended upon
+ target_name: str
+ edge_id: str
+ edge_kind: str
+ severity: str = SEVERITY_VIOLATION
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "rule_source": self.rule_source,
+ "rule_target": self.rule_target,
+ "rule_description": self.rule_description,
+ "source": self.source,
+ "source_name": self.source_name,
+ "target": self.target,
+ "target_name": self.target_name,
+ "edge_id": self.edge_id,
+ "edge_kind": self.edge_kind,
+ "severity": self.severity,
+ }
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> ConformanceViolation:
+ return cls(
+ rule_source=data.get("rule_source", ""),
+ rule_target=data.get("rule_target", ""),
+ rule_description=data.get("rule_description", ""),
+ source=data.get("source", ""),
+ source_name=data.get("source_name", ""),
+ target=data.get("target", ""),
+ target_name=data.get("target_name", ""),
+ edge_id=data.get("edge_id", ""),
+ edge_kind=data.get("edge_kind", ""),
+ severity=data.get("severity", SEVERITY_VIOLATION),
+ )
+
+
+@dataclass
+class ConformanceReport:
+ """The workspace's architecture governance result: violations + cycles."""
+
+ version: int = 1
+ generated_at: str = ""
+ rules_evaluated: int = 0
+ violations: list[ConformanceViolation] = field(default_factory=list)
+ cycles: list[DependencyCycle] = field(default_factory=list)
+
+ @property
+ def has_findings(self) -> bool:
+ return bool(self.violations or self.cycles)
+
+ @property
+ def violating_repos(self) -> list[str]:
+ repos: set[str] = set()
+ for v in self.violations:
+ repos.add(v.source.split("::", 1)[0])
+ repos.add(v.target.split("::", 1)[0])
+ return sorted(repos)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "version": self.version,
+ "generated_at": self.generated_at,
+ "rules_evaluated": self.rules_evaluated,
+ "violations": [v.to_dict() for v in self.violations],
+ "cycles": [c.to_dict() for c in self.cycles],
+ "violation_count": len(self.violations),
+ "cycle_count": len(self.cycles),
+ "violating_repos": self.violating_repos,
+ }
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> ConformanceReport:
+ return cls(
+ version=data.get("version", 1),
+ generated_at=data.get("generated_at", ""),
+ rules_evaluated=data.get("rules_evaluated", 0),
+ violations=[ConformanceViolation.from_dict(v) for v in data.get("violations", [])],
+ cycles=[DependencyCycle.from_dict(c) for c in data.get("cycles", [])],
+ )
+
+
+# ---------------------------------------------------------------------------
+# Checking (pure)
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class _CompiledRule:
+ """A rule with its source/target matchers precompiled."""
+
+ rule: ConformanceRule
+ source_pred: MatcherPredicate
+ target_pred: MatcherPredicate
+
+ def matches(self, src: SystemNode, tgt: SystemNode, tags_by_repo: dict[str, list[str]]) -> bool:
+ return self.source_pred(src, tags_by_repo) and self.target_pred(tgt, tags_by_repo)
+
+
+def _compile(rule: ConformanceRule) -> _CompiledRule:
+ return _CompiledRule(
+ rule=rule,
+ source_pred=compile_matcher(rule.source),
+ target_pred=compile_matcher(rule.target),
+ )
+
+
+def check_conformance(
+ graph: SystemGraph,
+ rules: list[ConformanceRule],
+ tags_by_repo: dict[str, list[str]] | None = None,
+) -> list[ConformanceViolation]:
+ """Return the structural dependencies that violate the deny rules.
+
+ For every structural edge ``source -> target``, a deny rule whose matchers
+ cover both ends raises a violation, unless an ``allow`` rule also covers the
+ edge (an explicit exception). Pure and O(edges x rules); the graph is
+ service-granular so that stays small.
+ """
+ tags_by_repo = tags_by_repo or {}
+ deny = [_compile(r) for r in rules if not r.allow]
+ allow = [_compile(r) for r in rules if r.allow]
+ if not deny:
+ return []
+
+ nodes_by_id = {n.id: n for n in graph.nodes}
+ violations: list[ConformanceViolation] = []
+
+ for edge in graph.edges:
+ if not edge.structural:
+ continue
+ src = nodes_by_id.get(edge.source)
+ tgt = nodes_by_id.get(edge.target)
+ if src is None or tgt is None:
+ continue
+ for compiled in deny:
+ if not compiled.matches(src, tgt, tags_by_repo):
+ continue
+ # A matching allow rule whitelists this specific edge.
+ if any(a.matches(src, tgt, tags_by_repo) for a in allow):
+ break
+ violations.append(
+ ConformanceViolation(
+ rule_source=compiled.rule.source,
+ rule_target=compiled.rule.target,
+ rule_description=compiled.rule.description,
+ source=src.id,
+ source_name=src.name,
+ target=tgt.id,
+ target_name=tgt.name,
+ edge_id=edge.id,
+ edge_kind=edge.kind,
+ )
+ )
+ break # one violation per edge — the first deny rule that fires
+
+ violations.sort(key=lambda v: (v.source, v.target, v.edge_kind))
+ return violations
+
+
+def build_conformance_report(
+ graph: SystemGraph,
+ rules: list[ConformanceRule],
+ tags_by_repo: dict[str, list[str]] | None = None,
+ *,
+ generated_at: str = "",
+) -> ConformanceReport:
+ """Assemble the full governance report: rule violations + dependency cycles."""
+ violations = check_conformance(graph, rules, tags_by_repo)
+ cycles = detect_cycles(graph)
+ return ConformanceReport(
+ generated_at=generated_at,
+ rules_evaluated=len(rules),
+ violations=violations,
+ cycles=cycles,
+ )
+
+
+def tags_by_repo_from_config(ws_config: WorkspaceConfig) -> dict[str, list[str]]:
+ """Build the repo-alias → tags map service nodes inherit for matching."""
+ return {entry.alias: list(entry.tags) for entry in ws_config.repos}
+
+
+# ---------------------------------------------------------------------------
+# Persistence
+# ---------------------------------------------------------------------------
+
+
+def save_conformance_report(report: ConformanceReport, workspace_root: Path) -> Path:
+ """Write the report to ``.repowise-workspace/conformance.json``."""
+ data_dir = ensure_workspace_data_dir(workspace_root)
+ out_path = data_dir / CONFORMANCE_FILENAME
+ out_path.write_text(
+ json.dumps(report.to_dict(), indent=2, ensure_ascii=False),
+ encoding="utf-8",
+ )
+ return out_path
+
+
+def load_conformance_report(workspace_root: Path) -> ConformanceReport | None:
+ """Load the report, or ``None`` if missing/unparseable."""
+ path = workspace_root / WORKSPACE_DATA_DIR / CONFORMANCE_FILENAME
+ if not path.is_file():
+ return None
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ return ConformanceReport.from_dict(data)
+ except Exception:
+ _log.warning("Failed to load conformance report from %s", path, exc_info=True)
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Orchestrator
+# ---------------------------------------------------------------------------
+
+
+def run_conformance_check(
+ ws_config: WorkspaceConfig,
+ workspace_root: Path,
+ graph: SystemGraph,
+ *,
+ generated_at: str = "",
+) -> ConformanceReport:
+ """Build and persist the conformance report from the latest system graph.
+
+ Called from ``run_cross_repo_hooks`` after the system graph is built. Cycle
+ detection runs even with no rules declared, so a workspace gets the cycle
+ half of governance for free.
+ """
+ report = build_conformance_report(
+ graph,
+ ws_config.conformance.rules,
+ tags_by_repo_from_config(ws_config),
+ generated_at=generated_at,
+ )
+ out_path = save_conformance_report(report, workspace_root)
+ _log.info(
+ "Conformance check complete: %d violation(s), %d cycle(s) from %d rule(s) → %s",
+ len(report.violations),
+ len(report.cycles),
+ report.rules_evaluated,
+ out_path,
+ )
+ return report
diff --git a/packages/core/src/repowise/core/workspace/cycles.py b/packages/core/src/repowise/core/workspace/cycles.py
new file mode 100644
index 000000000..43144f052
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/cycles.py
@@ -0,0 +1,154 @@
+"""Cross-repo dependency cycles — find circular service dependencies.
+
+A cycle in the *structural* edges of the system graph (``A`` depends on ``B``
+depends on … depends on ``A``) is an architecture smell: the services cannot be
+built, deployed, or reasoned about independently. This module finds those cycles
+over the same :class:`~repowise.core.workspace.system_graph.SystemGraph` every
+other workspace view reads.
+
+**Structural edges only.** Co-change is *behavioral* — two files changing
+together does not assert a dependency, so a co-change "loop" is not a cycle. We
+walk only ``edge.structural`` edges (http / grpc / event / package / db), exactly
+the distinction the system graph already encodes.
+
+**Reuse, not reinvention.** Cycle finding is delegated to NetworkX
+(``simple_cycles`` / ``strongly_connected_components``) — the same library the
+single-repo graph metrics use — rather than a hand-rolled DFS. The graph is
+service-granular (tens of nodes), so enumeration is cheap; we still cap the
+reported set (:data:`MAX_CYCLES`) and log truncation so a pathological graph
+never bloats the artifact silently.
+
+Pure and I/O-free: it consumes a ``SystemGraph`` and returns dataclasses.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from typing import Any
+
+from repowise.core.workspace.system_graph import SystemEdge, SystemGraph
+
+_log = logging.getLogger("repowise.workspace.cycles")
+
+# ---------------------------------------------------------------------------
+# Constants (single source of truth)
+# ---------------------------------------------------------------------------
+
+#: Cap on the number of elementary cycles reported. Governance only needs the
+#: representative loops, not every elementary cycle of a dense tangle; the true
+#: count is reported separately and truncation is logged (never silent).
+MAX_CYCLES = 50
+
+
+# ---------------------------------------------------------------------------
+# Data model
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class DependencyCycle:
+ """One elementary dependency cycle among services.
+
+ ``nodes`` lists the participating service ids in traversal order (each edge
+ goes ``nodes[i] -> nodes[i+1]``, and the last wraps back to the first).
+ ``edge_ids`` are the system-graph edges that form the loop, so a view can
+ highlight exactly those seams. ``length`` is the number of services.
+ """
+
+ nodes: list[str]
+ edge_ids: list[str]
+
+ @property
+ def length(self) -> int:
+ return len(self.nodes)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "nodes": self.nodes,
+ "edge_ids": self.edge_ids,
+ "length": self.length,
+ }
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> DependencyCycle:
+ return cls(
+ nodes=list(data.get("nodes", [])),
+ edge_ids=list(data.get("edge_ids", [])),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Detection (pure)
+# ---------------------------------------------------------------------------
+
+
+def _structural_adjacency(edges: list[SystemEdge]) -> dict[tuple[str, str], str]:
+ """Map each structural ``(source, target)`` pair to a representative edge id.
+
+ Parallel structural edges (e.g. http + package between the same services)
+ collapse onto one entry — a cycle highlights the seam, not every transport.
+ Self-loops (``source == target``) are kept: a service depending on itself is
+ a degenerate 1-cycle worth reporting.
+ """
+ adjacency: dict[tuple[str, str], str] = {}
+ for edge in edges:
+ if not edge.structural:
+ continue
+ key = (edge.source, edge.target)
+ adjacency.setdefault(key, edge.id)
+ return adjacency
+
+
+def _cycle_edges(nodes: list[str], adjacency: dict[tuple[str, str], str]) -> list[str]:
+ """Resolve the edge ids for the loop ``nodes[0] -> … -> nodes[0]``."""
+ edge_ids: list[str] = []
+ for i, src in enumerate(nodes):
+ tgt = nodes[(i + 1) % len(nodes)]
+ eid = adjacency.get((src, tgt))
+ if eid is not None:
+ edge_ids.append(eid)
+ return edge_ids
+
+
+def detect_cycles(graph: SystemGraph) -> list[DependencyCycle]:
+ """Return the elementary structural dependency cycles in *graph*.
+
+ Cycles are ordered shortest-first (the tightest loops are the most
+ actionable), then lexicographically for stability. Capped at
+ :data:`MAX_CYCLES`; truncation is logged. Returns ``[]`` when the structural
+ subgraph is acyclic or NetworkX is unavailable.
+ """
+ adjacency = _structural_adjacency(graph.edges)
+ if not adjacency:
+ return []
+
+ try:
+ import networkx as nx
+ except Exception: # pragma: no cover - networkx is a hard dependency
+ _log.warning("networkx unavailable; skipping cycle detection", exc_info=True)
+ return []
+
+ digraph = nx.DiGraph()
+ digraph.add_nodes_from(n.id for n in graph.nodes)
+ digraph.add_edges_from(adjacency.keys())
+
+ cycles: list[DependencyCycle] = []
+ try:
+ for raw in nx.simple_cycles(digraph):
+ edge_ids = _cycle_edges(raw, adjacency)
+ if edge_ids:
+ cycles.append(DependencyCycle(nodes=list(raw), edge_ids=edge_ids))
+ except Exception: # pragma: no cover - defensive
+ _log.warning("cycle enumeration failed", exc_info=True)
+ return []
+
+ cycles.sort(key=lambda c: (c.length, c.nodes))
+ if len(cycles) > MAX_CYCLES:
+ _log.info(
+ "Cycle detection found %d cycles; reporting the %d shortest.",
+ len(cycles),
+ MAX_CYCLES,
+ )
+ cycles = cycles[:MAX_CYCLES]
+ return cycles
diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.py
index 3cfff09cd..867924c03 100644
--- a/packages/core/src/repowise/core/workspace/update.py
+++ b/packages/core/src/repowise/core/workspace/update.py
@@ -709,9 +709,10 @@ async def run_cross_repo_hooks(
return
from .breaking_change import run_breaking_change_detection
+ from .conformance import run_conformance_check
from .contracts import ContractStore, load_contract_store, run_contract_extraction
from .cross_repo import CrossRepoOverlay, run_cross_repo_analysis
- from .system_graph import run_system_graph_build
+ from .system_graph import SystemGraph, run_system_graph_build
overlay = CrossRepoOverlay()
try:
@@ -733,8 +734,9 @@ async def run_cross_repo_hooks(
# System graph — the normalized service-granular structure every workspace
# view reads. Built last so it folds in the contracts and overlay above.
+ system_graph: SystemGraph | None = None
try:
- await run_system_graph_build(ws_config, workspace_root, store, overlay)
+ system_graph = await run_system_graph_build(ws_config, workspace_root, store, overlay)
except Exception:
_log.warning("System graph build failed", exc_info=True)
@@ -744,3 +746,11 @@ async def run_cross_repo_hooks(
run_breaking_change_detection(workspace_root, previous_store, store)
except Exception:
_log.warning("Breaking-change detection failed", exc_info=True)
+
+ # Conformance + cycles — check declared dependency rules and detect circular
+ # service dependencies over the freshly-built system graph.
+ if system_graph is not None:
+ try:
+ run_conformance_check(ws_config, workspace_root, system_graph)
+ except Exception:
+ _log.warning("Conformance check failed", exc_info=True)
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index 7de31e500..8399a232b 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -309,6 +309,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
logger.warning("workspace_stale_job_reset_failed", extra={"error": str(exc)})
from repowise.core.workspace.breaking_change import BREAKING_CHANGES_FILENAME
+ from repowise.core.workspace.conformance import CONFORMANCE_FILENAME
from repowise.core.workspace.contracts import CONTRACTS_FILENAME
from repowise.core.workspace.system_graph import SYSTEM_GRAPH_FILENAME
from repowise.server.mcp_server._enrichment import CrossRepoEnricher
@@ -317,11 +318,13 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
contracts_path = _Path(ws_root) / WORKSPACE_DATA_DIR / CONTRACTS_FILENAME
system_graph_path = _Path(ws_root) / WORKSPACE_DATA_DIR / SYSTEM_GRAPH_FILENAME
breaking_changes_path = _Path(ws_root) / WORKSPACE_DATA_DIR / BREAKING_CHANGES_FILENAME
+ conformance_path = _Path(ws_root) / WORKSPACE_DATA_DIR / CONFORMANCE_FILENAME
enricher = CrossRepoEnricher(
cross_repo_path,
contracts_path=contracts_path,
system_graph_path=system_graph_path,
breaking_changes_path=breaking_changes_path,
+ conformance_path=conformance_path,
)
if enricher.has_data or enricher.has_contract_data or enricher.has_system_graph:
app.state.cross_repo_enricher = enricher
diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.py
index bf4b936ff..9ccacaca4 100644
--- a/packages/server/src/repowise/server/mcp_server/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/__init__.py
@@ -1,4 +1,4 @@
-"""repowise MCP Server — 18 tools for AI coding assistants.
+"""repowise MCP Server — 19 tools for AI coding assistants.
Exposes the full repowise wiki as queryable tools via the MCP protocol.
Supports stdio transport (Claude Code, Cursor, Cline), streamable HTTP, and
@@ -39,6 +39,7 @@ from repowise.server.mcp_server._server import (
)
from repowise.server.mcp_server.tool_answer import get_answer
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
from repowise.server.mcp_server.tool_dead_code import get_dead_code
from repowise.server.mcp_server.tool_health import get_health
@@ -110,6 +111,7 @@ __all__ = [
"create_mcp_server",
"get_answer",
"get_blast_radius",
+ "get_conformance",
"get_context",
"get_dead_code",
"get_health",
diff --git a/packages/server/src/repowise/server/mcp_server/_enrichment.py b/packages/server/src/repowise/server/mcp_server/_enrichment.py
index defb54b3b..b34b28300 100644
--- a/packages/server/src/repowise/server/mcp_server/_enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/_enrichment.py
@@ -23,6 +23,7 @@ class CrossRepoEnricher:
contracts_path: Path | None = None,
system_graph_path: Path | None = None,
breaking_changes_path: Path | None = None,
+ conformance_path: Path | None = None,
) -> None:
self._co_changes: list[dict] = []
self._package_deps: list[dict] = []
@@ -49,10 +50,15 @@ class CrossRepoEnricher:
self._breaking_changes: dict | None = None
self._breaking_changes_by_repo: dict[str, list[dict]] = defaultdict(list)
+ # Conformance report — architecture rule violations + dependency cycles
+ # from the most recent update. Read-only pass-through.
+ self._conformance: dict | None = None
+
self._data_path = data_path
self._contracts_path = contracts_path
self._system_graph_path = system_graph_path
self._breaking_changes_path = breaking_changes_path
+ self._conformance_path = conformance_path
self._load(data_path)
if contracts_path is not None:
@@ -61,6 +67,8 @@ class CrossRepoEnricher:
self._load_system_graph(system_graph_path)
if breaking_changes_path is not None:
self._load_breaking_changes(breaking_changes_path)
+ if conformance_path is not None:
+ self._load_conformance(conformance_path)
def _load(self, data_path: Path) -> None:
"""Parse JSON and build indexes."""
@@ -207,6 +215,22 @@ class CrossRepoEnricher:
len(self._breaking_changes.get("changes", [])),
)
+ def _load_conformance(self, conformance_path: Path) -> None:
+ """Parse ``conformance.json`` (read-only pass-through to views)."""
+ if not conformance_path.is_file():
+ _log.debug("No conformance report at %s", conformance_path)
+ return
+ try:
+ self._conformance = json.loads(conformance_path.read_text(encoding="utf-8"))
+ except Exception:
+ _log.warning("Failed to parse conformance at %s", conformance_path, exc_info=True)
+ return
+ _log.debug(
+ "Conformance report loaded: %d violation(s), %d cycle(s)",
+ len(self._conformance.get("violations", [])),
+ len(self._conformance.get("cycles", [])),
+ )
+
def reload(self) -> None:
"""Re-read JSON files from disk and rebuild all indexes.
@@ -228,6 +252,7 @@ class CrossRepoEnricher:
self._system_graph = None
self._breaking_changes = None
self._breaking_changes_by_repo = defaultdict(list)
+ self._conformance = None
self._load(self._data_path)
if self._contracts_path is not None:
@@ -236,6 +261,8 @@ class CrossRepoEnricher:
self._load_system_graph(self._system_graph_path)
if self._breaking_changes_path is not None:
self._load_breaking_changes(self._breaking_changes_path)
+ if self._conformance_path is not None:
+ self._load_conformance(self._conformance_path)
_log.info(
"Cross-repo enricher reloaded: %d co-change edges, %d package deps, %d contract links",
@@ -276,6 +303,43 @@ class CrossRepoEnricher:
"""Return breaking changes whose provider lives in *repo_alias*."""
return self._breaking_changes_by_repo.get(repo_alias, [])
+ @property
+ def has_conformance(self) -> bool:
+ """True if a conformance report has been loaded."""
+ return self._conformance is not None
+
+ def get_conformance(self) -> dict | None:
+ """Return the raw conformance report (violations + cycles + rollups)."""
+ return self._conformance
+
+ @staticmethod
+ def _node_repo(node_id: str) -> str:
+ """Repo alias for a system-graph node id (``repo`` or ``repo::service``)."""
+ return node_id.split("::", 1)[0]
+
+ def get_conformance_for_repo(self, repo_alias: str) -> dict:
+ """Violations + cycles that involve *repo_alias*.
+
+ A violation involves the repo when either endpoint lives in it; a cycle
+ when any participating service does. Used by the ``get_risk`` PR-mode
+ directive to surface architecture findings a diff's repo participates in.
+ """
+ report = self._conformance
+ if not report:
+ return {"violations": [], "cycles": []}
+ violations = [
+ v
+ for v in report.get("violations", [])
+ if self._node_repo(v.get("source", "")) == repo_alias
+ or self._node_repo(v.get("target", "")) == repo_alias
+ ]
+ cycles = [
+ c
+ for c in report.get("cycles", [])
+ if any(self._node_repo(n) == repo_alias for n in c.get("nodes", []))
+ ]
+ return {"violations": violations, "cycles": cycles}
+
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/_server.py b/packages/server/src/repowise/server/mcp_server/_server.py
index b31f9bce0..138c18823 100644
--- a/packages/server/src/repowise/server/mcp_server/_server.py
+++ b/packages/server/src/repowise/server/mcp_server/_server.py
@@ -284,6 +284,7 @@ async def _lifespan(server: FastMCP):
try:
from repowise.core.workspace.breaking_change import BREAKING_CHANGES_FILENAME
from repowise.core.workspace.config import WORKSPACE_DATA_DIR
+ from repowise.core.workspace.conformance import CONFORMANCE_FILENAME
from repowise.core.workspace.contracts import CONTRACTS_FILENAME
from repowise.core.workspace.system_graph import SYSTEM_GRAPH_FILENAME
from repowise.server.mcp_server._enrichment import CrossRepoEnricher
@@ -292,11 +293,13 @@ async def _lifespan(server: FastMCP):
contracts_path = ws_root / WORKSPACE_DATA_DIR / CONTRACTS_FILENAME
system_graph_path = ws_root / WORKSPACE_DATA_DIR / SYSTEM_GRAPH_FILENAME
breaking_changes_path = ws_root / WORKSPACE_DATA_DIR / BREAKING_CHANGES_FILENAME
+ conformance_path = ws_root / WORKSPACE_DATA_DIR / CONFORMANCE_FILENAME
enricher = CrossRepoEnricher(
cross_repo_path,
contracts_path=contracts_path,
system_graph_path=system_graph_path,
breaking_changes_path=breaking_changes_path,
+ conformance_path=conformance_path,
)
if enricher.has_data or enricher.has_system_graph:
_state._cross_repo_enricher = enricher
diff --git a/packages/server/src/repowise/server/mcp_server/tool_conformance.py b/packages/server/src/repowise/server/mcp_server/tool_conformance.py
new file mode 100644
index 000000000..7db17b98d
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_conformance.py
@@ -0,0 +1,87 @@
+"""MCP Tool: get_conformance — architecture rule violations + cycles (workspace).
+
+Answers "does the live architecture obey the dependency rules we declared, and
+are there any circular service dependencies?" by reading the conformance report
+built during ``repowise update --workspace``. Read-only; the full report is also
+on ``GET /api/workspace/conformance``.
+"""
+
+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
+
+#: Inline caps so the agent payload stays tight; true counts are reported and the
+#: full set is on the REST endpoint.
+_MCP_VIOLATION_LIMIT = 25
+_MCP_CYCLE_LIMIT = 25
+
+
+async def get_conformance(repo: str | None = None) -> dict[str, Any]:
+ """Architecture conformance — dependency-rule violations + cycles.
+
+ Workspace-only. Reports cross-repo dependencies that violate the team's
+ declared allow/deny rules (e.g. ``frontend !-> db``) and any circular service
+ dependencies. Call before a refactor that changes service boundaries, or to
+ audit whether the live architecture still matches the intended one.
+
+ Args:
+ repo: optional repo alias — limit findings to those involving this repo.
+ """
+ if not _is_workspace_mode():
+ return {
+ "error": "get_conformance is only available in workspace mode.",
+ "_meta": _build_meta(),
+ }
+
+ enricher = _state._cross_repo_enricher
+ report = enricher.get_conformance() if enricher is not None else None
+ if not report:
+ return {
+ "error": (
+ "No conformance report is available yet. Run `repowise update "
+ "--workspace` to build cross-repo relationships, and declare rules "
+ "under `conformance:` in `.repowise-workspace.yaml`."
+ ),
+ "_meta": _build_meta(),
+ }
+
+ if repo:
+ scoped = enricher.get_conformance_for_repo(repo)
+ violations = scoped["violations"]
+ cycles = scoped["cycles"]
+ else:
+ violations = report.get("violations", [])
+ cycles = report.get("cycles", [])
+
+ shown_violations = violations[:_MCP_VIOLATION_LIMIT]
+ shown_cycles = cycles[:_MCP_CYCLE_LIMIT]
+
+ if violations or cycles:
+ summary = (
+ f"{len(violations)} architecture rule violation(s) and {len(cycles)} "
+ f"dependency cycle(s) from {report.get('rules_evaluated', 0)} declared rule(s)."
+ )
+ elif report.get("rules_evaluated", 0):
+ summary = "No conformance violations or dependency cycles detected."
+ else:
+ summary = (
+ "No conformance rules are declared; reporting dependency cycles only (none found)."
+ )
+
+ return {
+ "rules_evaluated": report.get("rules_evaluated", 0),
+ "violations": shown_violations,
+ "violations_truncated": max(0, len(violations) - len(shown_violations)),
+ "cycles": shown_cycles,
+ "cycles_truncated": max(0, len(cycles) - len(shown_cycles)),
+ "violation_count": len(violations),
+ "cycle_count": len(cycles),
+ "summary": summary,
+ "_meta": _build_meta(),
+ }
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk.py
index c015ef89e..7437c0024 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk.py
@@ -416,6 +416,10 @@ _XR_COCHANGE_LIMIT = 3
#: The full report is on GET /api/workspace/breaking-changes.
_BC_PROVIDER_LIMIT = 5
_BC_CONSUMER_LIMIT = 5
+#: Caps on the conformance directive — violations and cycles that touch the repo.
+#: The full report is on GET /api/workspace/conformance.
+_CF_VIOLATION_LIMIT = 5
+_CF_CYCLE_LIMIT = 3
def _breaking_change_directive(repo_alias: str) -> list[dict[str, Any]]:
@@ -464,6 +468,41 @@ def _breaking_change_directive(repo_alias: str) -> list[dict[str, Any]]:
return out
+def _conformance_directive(repo_alias: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ """Conformance half of the PR directive: architecture findings touching this repo.
+
+ Reads the persisted conformance report (rule violations + dependency cycles
+ over the system graph) and returns those that involve the changed repo, so a
+ diff that participates in a denied dependency or a circular dependency is
+ flagged. Returns two empty lists when not in workspace mode or no report is
+ available. Never raises.
+ """
+ violations: list[dict[str, Any]] = []
+ cycles: list[dict[str, Any]] = []
+ try:
+ if not _is_workspace_mode():
+ return violations, cycles
+ enricher = _state._cross_repo_enricher
+ if enricher is None or not getattr(enricher, "has_conformance", False):
+ return violations, cycles
+ scoped = enricher.get_conformance_for_repo(repo_alias)
+ for v in scoped.get("violations", [])[:_CF_VIOLATION_LIMIT]:
+ violations.append(
+ {
+ "source": v.get("source"),
+ "target": v.get("target"),
+ "rule": f"{v.get('rule_source')} !-> {v.get('rule_target')}",
+ "edge_kind": v.get("edge_kind"),
+ "description": v.get("rule_description") or None,
+ }
+ )
+ for c in scoped.get("cycles", [])[:_CF_CYCLE_LIMIT]:
+ cycles.append({"nodes": c.get("nodes", []), "length": c.get("length", 0)})
+ except Exception:
+ return [], []
+ return violations, cycles
+
+
def _cross_repo_directive(repo_alias: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
"""Cross-repo half of the PR directive: downstream services in other repos.
@@ -893,6 +932,18 @@ async def get_risk(
f"incompatibly, endangering {bc_consumers} consumer(s)."
)
+ # Architecture conformance — declared dependency-rule violations and
+ # dependency cycles this repo participates in. Governance-level truth,
+ # distinct from the topology / schema directives above.
+ conformance_violations, dependency_cycles = _conformance_directive(ctx.alias)
+ cf_suffix = ""
+ if conformance_violations or dependency_cycles:
+ cf_suffix = (
+ f" Conformance: {len(conformance_violations)} architecture rule "
+ f"violation(s), {len(dependency_cycles)} dependency cycle(s) involving "
+ f"this repo."
+ )
+
response["directive"] = {
"will_break": will_break,
"missing_cochanges": missing_cochanges,
@@ -900,6 +951,8 @@ async def get_risk(
"will_break_consumers": will_break_consumers,
"missing_cross_repo_cochanges": missing_cross_repo_cochanges,
"breaking_changes": breaking_changes,
+ "conformance_violations": conformance_violations,
+ "dependency_cycles": dependency_cycles,
"governance_risk": governance_risk,
"overall_risk_score": trimmed_blast.get("overall_risk_score"),
"summary": (
@@ -907,7 +960,7 @@ async def get_risk(
f"~{len(will_break)} downstream file(s) likely affected, "
f"{len(missing_cochanges)} historical co-changer(s) missing, "
f"{len(missing_tests)} file(s) without tests."
- f"{gov_suffix}{xr_suffix}{bc_suffix}"
+ f"{gov_suffix}{xr_suffix}{bc_suffix}{cf_suffix}"
),
}
else:
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index d7011f1c4..cb54c5885 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -24,6 +24,7 @@ from repowise.server.schemas import (
WorkspaceBreakingChangesResponse,
WorkspaceCoChangeEntry,
WorkspaceCoChangesResponse,
+ WorkspaceConformanceResponse,
WorkspaceContractEntry,
WorkspaceContractLinkEntry,
WorkspaceContractsResponse,
@@ -626,6 +627,56 @@ async def get_breaking_changes(
return WorkspaceBreakingChangesResponse(**report)
+# ---------------------------------------------------------------------------
+# GET /api/workspace/conformance
+# ---------------------------------------------------------------------------
+
+
[email protected]("/conformance", response_model=WorkspaceConformanceResponse)
+async def get_conformance(
+ ws_config=Depends(get_workspace_config),
+ enricher=Depends(get_cross_repo_enricher),
+ repo: str | None = Query(
+ None, description="Filter to violations/cycles that involve this repo alias."
+ ),
+):
+ """Architecture conformance — declared dependency-rule violations + cycles.
+
+ Computed during the most recent ``repowise update --workspace`` by checking
+ the workspace's declared allow/deny rules against the system graph and
+ detecting circular service dependencies. Returns an empty report (not 404)
+ when no rules are declared, no findings exist, or no report has been built.
+ """
+ _require_workspace(ws_config)
+
+ report = enricher.get_conformance() if enricher is not None else None
+ if not report:
+ return WorkspaceConformanceResponse()
+
+ if not repo:
+ return WorkspaceConformanceResponse(**report)
+
+ # Narrow to findings that involve the repo, recomputing rollups so the
+ # response stays self-consistent.
+ scoped = enricher.get_conformance_for_repo(repo)
+ violations = scoped["violations"]
+ cycles = scoped["cycles"]
+ violating_repos = sorted(
+ {v.get("source", "").split("::", 1)[0] for v in violations}
+ | {v.get("target", "").split("::", 1)[0] for v in violations}
+ )
+ return WorkspaceConformanceResponse(
+ version=report.get("version", 1),
+ generated_at=report.get("generated_at", ""),
+ rules_evaluated=report.get("rules_evaluated", 0),
+ violations=violations,
+ cycles=cycles,
+ violation_count=len(violations),
+ cycle_count=len(cycles),
+ violating_repos=violating_repos,
+ )
+
+
# ---------------------------------------------------------------------------
# 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 ee1e2119e..f7996843f 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -160,11 +160,14 @@ from .workspace import (
WorkspaceBreakingChangesResponse,
WorkspaceCoChangeEntry,
WorkspaceCoChangesResponse,
+ WorkspaceConformanceResponse,
+ WorkspaceConformanceViolation,
WorkspaceContractEntry,
WorkspaceContractLinkEntry,
WorkspaceContractsResponse,
WorkspaceContractSummary,
WorkspaceCrossRepoSummary,
+ WorkspaceDependencyCycle,
WorkspaceExtractionDiagnostics,
WorkspaceGraphEdge,
WorkspaceGraphNode,
@@ -303,11 +306,14 @@ __all__ = [
"WorkspaceBreakingChangesResponse",
"WorkspaceImpactedConsumer",
"WorkspaceCoChangesResponse",
+ "WorkspaceConformanceResponse",
+ "WorkspaceConformanceViolation",
"WorkspaceContractEntry",
"WorkspaceContractLinkEntry",
"WorkspaceContractSummary",
"WorkspaceContractsResponse",
"WorkspaceCrossRepoSummary",
+ "WorkspaceDependencyCycle",
"WorkspaceExtractionDiagnostics",
"WorkspaceGraphEdge",
"WorkspaceGraphNode",
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index 9f702e9c7..2c91d0a6c 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -287,3 +287,39 @@ class WorkspaceBreakingChangesResponse(BaseModel):
impacted_repos: list[str] = []
impacted_services: list[str] = []
total_impacted_consumers: int = 0
+
+
+# ---------------------------------------------------------------------------
+# Architecture conformance — rule violations + dependency cycles.
+# Mirrors repowise.core.workspace.{conformance,cycles}.
+# ---------------------------------------------------------------------------
+
+
+class WorkspaceConformanceViolation(BaseModel):
+ rule_source: str
+ rule_target: str
+ rule_description: str = ""
+ source: str
+ source_name: str
+ target: str
+ target_name: str
+ edge_id: str
+ edge_kind: str
+ severity: str = "violation"
+
+
+class WorkspaceDependencyCycle(BaseModel):
+ nodes: list[str] = []
+ edge_ids: list[str] = []
+ length: int = 0
+
+
+class WorkspaceConformanceResponse(BaseModel):
+ version: int = 1
+ generated_at: str = ""
+ rules_evaluated: int = 0
+ violations: list[WorkspaceConformanceViolation] = []
+ cycles: list[WorkspaceDependencyCycle] = []
+ violation_count: int = 0
+ cycle_count: int = 0
+ violating_repos: list[str] = []
diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.ts
index ddf1ee5ed..175a0ad1c 100644
--- a/packages/types/src/workspace.ts
+++ b/packages/types/src/workspace.ts
@@ -284,3 +284,97 @@ export interface BreakingChangeReport {
impacted_services: string[];
total_impacted_consumers: number;
}
+
+// ---------------------------------------------------------------------------
+// Architecture conformance — declared dependency rules + dependency cycles.
+// A team declares allow/deny dependency rules in `.repowise-workspace.yaml`;
+// the checker reports structural dependencies that violate them, plus any
+// circular service dependencies. Mirrors `repowise.core.workspace.conformance`
+// and `repowise.core.workspace.cycles`.
+// ---------------------------------------------------------------------------
+
+/**
+ * One conformance rule. `source` / `target` are matchers: `"*"` (any service),
+ * `"tag:<name>"` (repo tag), or a glob over node id / repo / name. `allow=false`
+ * (default) denies the dependency; `allow=true` whitelists an exception.
+ */
+export interface ConformanceRule {
+ source: string;
+ target: string;
+ allow: boolean;
+ description: string;
+}
+
+/** A structural dependency that a deny rule forbids. */
+export interface ConformanceViolation {
+ /** The rule's source matcher that fired. */
+ rule_source: string;
+ /** The rule's target matcher that fired. */
+ rule_target: string;
+ rule_description: string;
+ /** Offending service node id (depends on `target`). */
+ source: string;
+ source_name: string;
+ /** Service node id depended upon. */
+ target: string;
+ target_name: string;
+ /** The system-graph edge that violates the rule (for map badging). */
+ edge_id: string;
+ edge_kind: SystemEdgeKind;
+ severity: string;
+}
+
+/** One elementary circular dependency among services (`nodes[i] -> nodes[i+1]`, wrapping). */
+export interface DependencyCycle {
+ /** Participating service ids in traversal order. */
+ nodes: string[];
+ /** System-graph edge ids forming the loop. */
+ edge_ids: string[];
+ /** Number of services in the cycle. */
+ length: number;
+}
+
+export interface ConformanceReport {
+ version: number;
+ generated_at: string;
+ /** How many rules were declared and evaluated. */
+ rules_evaluated: number;
+ violations: ConformanceViolation[];
+ cycles: DependencyCycle[];
+ violation_count: number;
+ cycle_count: number;
+ /** Distinct repos participating in a violation. */
+ violating_repos: string[];
+}
+
+// ---------------------------------------------------------------------------
+// Dependency-structure matrix (DSM) — a dense governance view derived purely
+// from the system graph + conformance report (built client-side, no endpoint).
+// Services index both axes; a cell is the relationship from the row service to
+// the column service.
+// ---------------------------------------------------------------------------
+
+/** One DSM cell: the dependency from `from_id` (row) on `to_id` (column). */
+export interface DsmCell {
+ from_id: string;
+ to_id: string;
+ /** True when at least one structural edge runs row → column. */
+ present: boolean;
+ /** The dominant edge kind for the cell, or null when empty. */
+ kind: SystemEdgeKind | null;
+ /** The cell's edge ids (for drill-down / highlighting). */
+ edge_ids: string[];
+ /** Row → column dependency violates a declared rule. */
+ violation: boolean;
+ /** Row → column edge participates in a dependency cycle. */
+ cycle: boolean;
+}
+
+export interface DsmMatrix {
+ /** Service ids in axis order (rows and columns share this order). */
+ axis: string[];
+ /** Display names parallel to `axis`. */
+ labels: string[];
+ /** Row-major cells: `cells[i][j]` is the dependency of `axis[i]` on `axis[j]`. */
+ cells: DsmCell[][];
+}
diff --git a/packages/ui/__tests__/workspace/dsm.test.tsx b/packages/ui/__tests__/workspace/dsm.test.tsx
new file mode 100644
index 000000000..ac56fb8b2
--- /dev/null
+++ b/packages/ui/__tests__/workspace/dsm.test.tsx
@@ -0,0 +1,135 @@
+import { describe, it, expect, vi } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
+import type {
+ ConformanceReport,
+ DsmCell,
+ SystemEdge,
+ SystemGraph,
+ SystemNode,
+} from "@repowise-dev/types";
+import { buildDsm } from "../../src/workspace/dsm/dsm";
+import { DsmMatrixView } from "../../src/workspace/dsm/dsm-matrix";
+import { SystemMapConformancePanel } from "../../src/workspace/system-map/system-map-conformance-panel";
+
+function node(id: string, over: Partial<SystemNode> = {}): SystemNode {
+ return {
+ id,
+ repo: id.split("::")[0] ?? id,
+ service_path: null,
+ name: id,
+ kind: "service",
+ provider_count: 0,
+ consumer_count: 0,
+ contract_types: [],
+ is_orphan_provider: false,
+ is_orphan_consumer: false,
+ is_isolated: false,
+ ...over,
+ };
+}
+
+function edge(source: string, target: string, over: Partial<SystemEdge> = {}): SystemEdge {
+ return {
+ id: `${source}->${target}`,
+ source,
+ target,
+ kind: "http",
+ match_type: "exact",
+ confidence: 0.9,
+ weight: 1,
+ structural: true,
+ contract_refs: [],
+ ...over,
+ };
+}
+
+function graph(nodes: SystemNode[], edges: SystemEdge[]): SystemGraph {
+ return { version: 1, generated_at: "t", nodes, edges, diagnostics: {} as never };
+}
+
+const g = graph([node("api"), node("db"), node("web")], [edge("web", "api"), edge("api", "db")]);
+
+describe("DsmMatrixView", () => {
+ it("renders a grid with the service axis labels", () => {
+ render(<DsmMatrixView matrix={buildDsm(g)} />);
+ expect(screen.getByRole("grid", { name: /dependency-structure matrix/i })).toBeInTheDocument();
+ // each service appears as a row + column header
+ expect(screen.getAllByText("api").length).toBeGreaterThanOrEqual(2);
+ expect(screen.getByText(/3/)).toBeInTheDocument(); // 3 services summary
+ });
+
+ it("shows the empty state for an empty graph", () => {
+ render(<DsmMatrixView matrix={buildDsm(null)} />);
+ expect(screen.getByText(/no services to chart/i)).toBeInTheDocument();
+ });
+
+ it("fires onSelectCell for a present cell", () => {
+ const onSelect = vi.fn();
+ render(<DsmMatrixView matrix={buildDsm(g)} onSelectCell={onSelect} />);
+ const cells = screen.getAllByRole("gridcell");
+ // Click the web->api dependency cell (present) by finding one with a title.
+ const present = cells.find((c) => c.getAttribute("title")?.includes("→"));
+ expect(present).toBeDefined();
+ fireEvent.click(present!);
+ expect(onSelect).toHaveBeenCalled();
+ const arg = onSelect.mock.calls[0]![0] as DsmCell;
+ expect(arg.present).toBe(true);
+ });
+});
+
+function report(over: Partial<ConformanceReport> = {}): ConformanceReport {
+ const violations = over.violations ?? [];
+ const cycles = over.cycles ?? [];
+ return {
+ version: 1,
+ generated_at: "t",
+ rules_evaluated: 1,
+ violations,
+ cycles,
+ violation_count: violations.length,
+ cycle_count: cycles.length,
+ violating_repos: [],
+ ...over,
+ };
+}
+
+describe("SystemMapConformancePanel", () => {
+ it("lists a violation and its rule", () => {
+ render(
+ <SystemMapConformancePanel
+ report={report({
+ violations: [
+ {
+ rule_source: "frontend",
+ rule_target: "db",
+ rule_description: "no direct db",
+ source: "frontend",
+ source_name: "frontend",
+ target: "db",
+ target_name: "db",
+ edge_id: "frontend->db",
+ edge_kind: "http",
+ severity: "violation",
+ },
+ ],
+ })}
+ onClear={() => {}}
+ />,
+ );
+ expect(screen.getByText(/architecture conformance/i)).toBeInTheDocument();
+ expect(screen.getByText(/frontend !-> db/)).toBeInTheDocument();
+ expect(screen.getByText(/no direct db/)).toBeInTheDocument();
+ });
+
+ it("shows the clean state when there are no findings", () => {
+ render(<SystemMapConformancePanel report={report()} onClear={() => {}} />);
+ expect(screen.getByText(/no rule violations or dependency cycles/i)).toBeInTheDocument();
+ });
+
+ it("renders nothing when the report is null", () => {
+ const { container } = render(
+ <SystemMapConformancePanel report={null} onClear={() => {}} />,
+ );
+ expect(container.firstChild).toBeNull();
+ });
+});
diff --git a/packages/ui/__tests__/workspace/system-map-logic.test.ts b/packages/ui/__tests__/workspace/system-map-logic.test.ts
index 0fe1d5bce..6a821c67e 100644
--- a/packages/ui/__tests__/workspace/system-map-logic.test.ts
+++ b/packages/ui/__tests__/workspace/system-map-logic.test.ts
@@ -15,7 +15,14 @@ import {
impactBadgeTone,
} from "../../src/workspace/system-map/blast-radius";
import { buildBreakingChangeOverlay } from "../../src/workspace/system-map/breaking-changes";
-import type { BreakingChange, BreakingChangeReport, CrossRepoBlastRadius } from "@repowise-dev/types";
+import { buildConformanceOverlay } from "../../src/workspace/system-map/conformance";
+import { buildDsm } from "../../src/workspace/dsm/dsm";
+import type {
+ BreakingChange,
+ BreakingChangeReport,
+ ConformanceReport,
+ CrossRepoBlastRadius,
+} from "@repowise-dev/types";
function node(id: string, repo: string, over: Partial<SystemNode> = {}): SystemNode {
return {
@@ -346,3 +353,136 @@ describe("buildBreakingChangeOverlay", () => {
expect(buildBreakingChangeOverlay(g, null)).toEqual({});
});
});
+
+function conformanceReport(over: Partial<ConformanceReport> = {}): ConformanceReport {
+ const violations = over.violations ?? [];
+ const cycles = over.cycles ?? [];
+ return {
+ version: 1,
+ generated_at: "t",
+ rules_evaluated: 1,
+ violations,
+ cycles,
+ violation_count: violations.length,
+ cycle_count: cycles.length,
+ violating_repos: [],
+ ...over,
+ };
+}
+
+describe("buildConformanceOverlay", () => {
+ const g = graph(
+ [node("frontend", "frontend"), node("db", "db"), node("api", "api")],
+ [edge("frontend", "db"), edge("db", "frontend"), edge("frontend", "api")],
+ );
+
+ it("badges violating edges danger and highlights both endpoints", () => {
+ const overlay = buildConformanceOverlay(
+ g,
+ conformanceReport({
+ violations: [
+ {
+ rule_source: "frontend",
+ rule_target: "db",
+ rule_description: "",
+ source: "frontend",
+ source_name: "frontend",
+ target: "db",
+ target_name: "db",
+ edge_id: "frontend->db",
+ edge_kind: "http",
+ severity: "violation",
+ },
+ ],
+ }),
+ );
+ expect(overlay.edgeBadges?.["frontend->db"]).toEqual({ label: "violation", tone: "danger" });
+ expect(overlay.nodeBadges?.frontend).toEqual({ label: "violation", tone: "danger" });
+ expect(overlay.nodeBadges?.db).toEqual({ label: "violation", tone: "danger" });
+ // Additive: nothing dimmed.
+ expect(overlay.dimNodeIds).toBeUndefined();
+ });
+
+ it("badges cycle edges warning and never overrides a violation badge", () => {
+ const overlay = buildConformanceOverlay(
+ g,
+ conformanceReport({
+ violations: [
+ {
+ rule_source: "frontend",
+ rule_target: "db",
+ rule_description: "",
+ source: "frontend",
+ source_name: "frontend",
+ target: "db",
+ target_name: "db",
+ edge_id: "frontend->db",
+ edge_kind: "http",
+ severity: "violation",
+ },
+ ],
+ cycles: [{ nodes: ["frontend", "db"], edge_ids: ["frontend->db", "db->frontend"], length: 2 }],
+ }),
+ );
+ // The shared edge keeps its violation badge (danger), not "cycle".
+ expect(overlay.edgeBadges?.["frontend->db"]).toEqual({ label: "violation", tone: "danger" });
+ // The other cycle edge gets the cycle badge.
+ expect(overlay.edgeBadges?.["db->frontend"]).toEqual({ label: "cycle", tone: "warning" });
+ });
+
+ it("returns an empty overlay with no findings", () => {
+ expect(buildConformanceOverlay(g, conformanceReport())).toEqual({});
+ expect(buildConformanceOverlay(g, null)).toEqual({});
+ });
+});
+
+describe("buildDsm", () => {
+ const g = graph(
+ [node("api", "api"), node("db", "db"), node("web", "web")],
+ [edge("web", "api"), edge("api", "db", { kind: "grpc" })],
+ );
+
+ it("places a present, kind-tagged cell for each dependency", () => {
+ const dsm = buildDsm(g);
+ // axis sorted by repo: api, db, web
+ expect(dsm.axis).toEqual(["api", "db", "web"]);
+ const cell = (from: string, to: string) =>
+ dsm.cells[dsm.axis.indexOf(from)]![dsm.axis.indexOf(to)]!;
+ expect(cell("web", "api").present).toBe(true);
+ expect(cell("api", "db").present).toBe(true);
+ expect(cell("api", "db").kind).toBe("grpc");
+ // No reverse dependency.
+ expect(cell("db", "api").present).toBe(false);
+ });
+
+ it("flags violation and cycle cells from the report", () => {
+ const dsm = buildDsm(
+ g,
+ conformanceReport({
+ violations: [
+ {
+ rule_source: "web",
+ rule_target: "api",
+ rule_description: "",
+ source: "web",
+ source_name: "web",
+ target: "api",
+ target_name: "api",
+ edge_id: "web->api",
+ edge_kind: "http",
+ severity: "violation",
+ },
+ ],
+ cycles: [{ nodes: ["api", "db"], edge_ids: ["api->db"], length: 2 }],
+ }),
+ );
+ const cell = (from: string, to: string) =>
+ dsm.cells[dsm.axis.indexOf(from)]![dsm.axis.indexOf(to)]!;
+ expect(cell("web", "api").violation).toBe(true);
+ expect(cell("api", "db").cycle).toBe(true);
+ });
+
+ it("returns an empty matrix for an empty graph", () => {
+ expect(buildDsm(null)).toEqual({ axis: [], labels: [], cells: [] });
+ });
+});
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 0d5a424dd..bf953a813 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -61,6 +61,7 @@
"./dashboard/*": "./src/dashboard/*.tsx",
"./workspace": "./src/workspace/index.ts",
"./workspace/system-map": "./src/workspace/system-map/index.ts",
+ "./workspace/dsm": "./src/workspace/dsm/index.ts",
"./workspace/*": "./src/workspace/*.tsx",
"./jobs": "./src/jobs/index.ts",
"./jobs/*": "./src/jobs/*.tsx",
diff --git a/packages/ui/src/workspace/dsm/dsm-matrix.tsx b/packages/ui/src/workspace/dsm/dsm-matrix.tsx
new file mode 100644
index 000000000..a78a6da8e
--- /dev/null
+++ b/packages/ui/src/workspace/dsm/dsm-matrix.tsx
@@ -0,0 +1,226 @@
+"use client";
+
+/**
+ * DSM grid — renders a `DsmMatrix` as a services × services table. Rows depend on
+ * columns: a filled cell `[row][col]` means the row service depends on the column
+ * service, tinted by the dominant edge kind. Rule violations are ringed red,
+ * dependency-cycle cells amber. The diagonal is inert (a service vs itself).
+ *
+ * Pure presentation: the host builds the matrix with `buildDsm` and passes it in.
+ * Designed to scale — the cell grid is plain CSS, no per-cell React Flow.
+ */
+
+import { useMemo, useState } from "react";
+import type { DsmCell, DsmMatrix } from "@repowise-dev/types";
+import { EmptyState } from "../../shared/empty-state";
+import { edgeKindStyle } from "../system-map/edge-kinds";
+
+export interface DsmMatrixViewProps {
+ matrix: DsmMatrix;
+ /** Optional click handler for a present cell (drill to the dependency). */
+ onSelectCell?: (cell: DsmCell) => void;
+}
+
+const CELL = 30;
+const HEADER = 150;
+
+function cellBackground(cell: DsmCell, isDiagonal: boolean): string {
+ if (isDiagonal) 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)";
+ const color = edgeKindStyle(cell.kind ?? "http").color;
+ return `color-mix(in srgb, ${color} 34%, transparent)`;
+}
+
+function cellRing(cell: DsmCell): string {
+ if (cell.violation) return "inset 0 0 0 2px var(--color-risk-high)";
+ if (cell.cycle) return "inset 0 0 0 2px var(--color-warning)";
+ return "none";
+}
+
+export function DsmMatrixView({ matrix, onSelectCell }: DsmMatrixViewProps) {
+ const [hover, setHover] = useState<{ row: number; col: number } | null>(null);
+
+ const counts = useMemo(() => {
+ let present = 0;
+ let violations = 0;
+ let cycles = 0;
+ for (const row of matrix.cells) {
+ for (const cell of row) {
+ if (cell.present) present += 1;
+ if (cell.violation) violations += 1;
+ if (cell.cycle) cycles += 1;
+ }
+ }
+ return { present, violations, cycles };
+ }, [matrix]);
+
+ if (matrix.axis.length === 0) {
+ return (
+ <EmptyState
+ title="No services to chart"
+ description="The dependency-structure matrix appears once the workspace has indexed services with cross-repo relationships."
+ />
+ );
+ }
+
+ const n = matrix.axis.length;
+
+ return (
+ <div>
+ <div
+ style={{
+ display: "flex",
+ gap: 16,
+ fontSize: 12,
+ color: "var(--color-text-tertiary)",
+ marginBottom: 10,
+ }}
+ >
+ <span>
+ <strong style={{ color: "var(--color-text-secondary)" }}>{n}</strong> services
+ </span>
+ <span>
+ <strong style={{ color: "var(--color-text-secondary)" }}>{counts.present}</strong>{" "}
+ dependencies
+ </span>
+ {counts.violations > 0 && (
+ <span style={{ color: "var(--color-risk-high)" }}>{counts.violations} violation(s)</span>
+ )}
+ {counts.cycles > 0 && (
+ <span style={{ color: "var(--color-warning)" }}>{counts.cycles} cycle cell(s)</span>
+ )}
+ </div>
+
+ <div style={{ overflow: "auto", maxWidth: "100%" }}>
+ <div
+ role="grid"
+ aria-label="Dependency-structure matrix"
+ style={{
+ display: "grid",
+ gridTemplateColumns: `${HEADER}px repeat(${n}, ${CELL}px)`,
+ width: "max-content",
+ fontSize: 11,
+ }}
+ >
+ {/* Top-left corner + column headers */}
+ <div style={{ position: "sticky", left: 0, zIndex: 2, background: "var(--color-bg-canvas)" }} />
+ {matrix.labels.map((label, j) => (
+ <div
+ key={`col-${matrix.axis[j]}`}
+ title={matrix.axis[j]}
+ style={{
+ height: HEADER,
+ display: "flex",
+ alignItems: "flex-end",
+ justifyContent: "center",
+ color:
+ hover?.col === j
+ ? "var(--color-text-primary)"
+ : "var(--color-text-tertiary)",
+ writingMode: "vertical-rl",
+ transform: "rotate(180deg)",
+ whiteSpace: "nowrap",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ paddingBottom: 4,
+ }}
+ >
+ {label}
+ </div>
+ ))}
+
+ {/* Rows */}
+ {matrix.cells.map((row, i) => (
+ <RowCells
+ key={`row-${matrix.axis[i]}`}
+ i={i}
+ row={row}
+ label={matrix.labels[i] ?? ""}
+ axisId={matrix.axis[i] ?? ""}
+ hover={hover}
+ onHover={setHover}
+ {...(onSelectCell ? { onSelectCell } : {})}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function RowCells({
+ i,
+ row,
+ label,
+ axisId,
+ hover,
+ onHover,
+ onSelectCell,
+}: {
+ i: number;
+ row: DsmCell[];
+ label: string;
+ axisId: string;
+ hover: { row: number; col: number } | null;
+ onHover: (h: { row: number; col: number } | null) => void;
+ onSelectCell?: (cell: DsmCell) => void;
+}) {
+ return (
+ <>
+ <div
+ title={axisId}
+ style={{
+ position: "sticky",
+ left: 0,
+ zIndex: 1,
+ height: CELL,
+ display: "flex",
+ alignItems: "center",
+ paddingRight: 8,
+ justifyContent: "flex-end",
+ whiteSpace: "nowrap",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ background: "var(--color-bg-canvas)",
+ color: hover?.row === i ? "var(--color-text-primary)" : "var(--color-text-secondary)",
+ }}
+ >
+ {label}
+ </div>
+ {row.map((cell, j) => {
+ const isDiagonal = i === j;
+ 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;
+ return (
+ <div
+ key={`cell-${i}-${j}`}
+ role="gridcell"
+ title={title}
+ onMouseEnter={() => onHover({ row: i, col: j })}
+ onMouseLeave={() => onHover(null)}
+ onClick={interactive ? () => onSelectCell?.(cell) : undefined}
+ style={{
+ width: CELL,
+ height: CELL,
+ boxSizing: "border-box",
+ border: "1px solid var(--color-border-subtle)",
+ background: cellBackground(cell, isDiagonal),
+ boxShadow: cellRing(cell),
+ cursor: interactive ? "pointer" : "default",
+ outline:
+ hover && (hover.row === i || hover.col === j)
+ ? "1px solid var(--color-border-default)"
+ : "none",
+ }}
+ />
+ );
+ })}
+ </>
+ );
+}
diff --git a/packages/ui/src/workspace/dsm/dsm.ts b/packages/ui/src/workspace/dsm/dsm.ts
new file mode 100644
index 000000000..2e66d88ed
Binary files /dev/null and b/packages/ui/src/workspace/dsm/dsm.ts differ
diff --git a/packages/ui/src/workspace/dsm/index.ts b/packages/ui/src/workspace/dsm/index.ts
new file mode 100644
index 000000000..2890c2053
--- /dev/null
+++ b/packages/ui/src/workspace/dsm/index.ts
@@ -0,0 +1,9 @@
+/**
+ * Dependency-structure matrix (DSM) — the dense governance view over the system
+ * graph. `buildDsm` reshapes the graph (+ conformance overlays) into a matrix;
+ * `DsmMatrixView` renders it. Both are pure over the shared `SystemGraph` /
+ * `ConformanceReport` types, so the hosted frontend reuses them unchanged.
+ */
+
+export { buildDsm } from "./dsm";
+export { DsmMatrixView, type DsmMatrixViewProps } from "./dsm-matrix";
diff --git a/packages/ui/src/workspace/system-map/conformance.ts b/packages/ui/src/workspace/system-map/conformance.ts
new file mode 100644
index 000000000..57298dbc3
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/conformance.ts
@@ -0,0 +1,63 @@
+/**
+ * Conformance overlay — turns a `ConformanceReport` (computed by the core / REST
+ * layer) into a `SystemMapOverlay` the Live System Map renders without any
+ * component change. Edges that violate a declared dependency rule are badged
+ * "violation" and highlighted; edges participating in a dependency cycle are
+ * badged "cycle". The offending services carry a node badge too. Additive (no
+ * dimming): the whole map stays legible with the governance seams called out.
+ * The Phase 5 attach point promised by the Phase 2 overlay API.
+ */
+
+import type { ConformanceReport, SystemGraph } from "@repowise-dev/types";
+import type { SystemMapBadge, SystemMapOverlay } from "./types";
+
+/**
+ * Build the governance overlay for a conformance report. Returns an empty
+ * overlay when there are no findings, so passing it through is always safe.
+ */
+export function buildConformanceOverlay(
+ graph: SystemGraph,
+ report: ConformanceReport | null | undefined,
+): SystemMapOverlay {
+ if (!report || (report.violations.length === 0 && report.cycles.length === 0)) {
+ return {};
+ }
+
+ const nodeBadges: Record<string, SystemMapBadge> = {};
+ const edgeBadges: Record<string, SystemMapBadge> = {};
+ const highlightEdgeIds = new Set<string>();
+ const highlightNodeIds = new Set<string>();
+
+ // Rule violations — danger. Badge the offending edge and both endpoints.
+ for (const v of report.violations) {
+ if (v.edge_id) {
+ highlightEdgeIds.add(v.edge_id);
+ edgeBadges[v.edge_id] = { label: "violation", tone: "danger" };
+ }
+ for (const nid of [v.source, v.target]) {
+ highlightNodeIds.add(nid);
+ if (!nodeBadges[nid]) nodeBadges[nid] = { label: "violation", tone: "danger" };
+ }
+ }
+
+ // Dependency cycles — warning (a smell, not an explicit policy breach). Don't
+ // override an existing violation badge on the same edge/node.
+ for (const cycle of report.cycles) {
+ for (const eid of cycle.edge_ids) {
+ highlightEdgeIds.add(eid);
+ if (!edgeBadges[eid]) edgeBadges[eid] = { label: "cycle", tone: "warning" };
+ }
+ for (const nid of cycle.nodes) {
+ highlightNodeIds.add(nid);
+ if (!nodeBadges[nid]) nodeBadges[nid] = { label: "cycle", tone: "warning" };
+ }
+ }
+
+ const overlay: SystemMapOverlay = { nodeBadges };
+ if (highlightNodeIds.size > 0) overlay.highlightNodeIds = highlightNodeIds;
+ if (highlightEdgeIds.size > 0) {
+ overlay.highlightEdgeIds = highlightEdgeIds;
+ overlay.edgeBadges = edgeBadges;
+ }
+ return overlay;
+}
diff --git a/packages/ui/src/workspace/system-map/index.ts b/packages/ui/src/workspace/system-map/index.ts
index 7b84b6698..7235d66c2 100644
--- a/packages/ui/src/workspace/system-map/index.ts
+++ b/packages/ui/src/workspace/system-map/index.ts
@@ -15,6 +15,11 @@ export {
type SystemMapBreakingPanelProps,
} from "./system-map-breaking-panel";
export { buildBreakingChangeOverlay } from "./breaking-changes";
+export {
+ SystemMapConformancePanel,
+ type SystemMapConformancePanelProps,
+} from "./system-map-conformance-panel";
+export { buildConformanceOverlay } from "./conformance";
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-conformance-panel.tsx b/packages/ui/src/workspace/system-map/system-map-conformance-panel.tsx
new file mode 100644
index 000000000..d46200924
--- /dev/null
+++ b/packages/ui/src/workspace/system-map/system-map-conformance-panel.tsx
@@ -0,0 +1,247 @@
+"use client";
+
+/**
+ * Governance rail for the Live System Map. Given a `ConformanceReport`, it lists
+ * the dependency-rule violations (the explicit policy breaches) and the
+ * dependency cycles (the structural smells), each linking to the services
+ * involved. Pure presentation: the host owns the fetch and passes the report in;
+ * the violation/cycle badges ride the map's overlay prop.
+ */
+
+import { ShieldAlert, RefreshCw, X } from "lucide-react";
+import type {
+ ConformanceReport,
+ ConformanceViolation,
+ DependencyCycle,
+} from "@repowise-dev/types";
+
+export interface SystemMapConformancePanelProps {
+ report: ConformanceReport | null;
+ loading?: boolean;
+ /** Focus a service on the map (optional). */
+ onSelectNode?: (nodeId: string) => void;
+ onClear: () => void;
+}
+
+const panelStyle: React.CSSProperties = {
+ position: "absolute",
+ top: 12,
+ right: 12,
+ width: 340,
+ maxHeight: "calc(100% - 24px)",
+ overflowY: "auto",
+ background: "var(--color-bg-elevated)",
+ border: "1px solid var(--color-border-default)",
+ borderRadius: 10,
+ boxShadow: "0 8px 24px rgba(0,0,0,0.28)",
+ zIndex: 4,
+ fontSize: 12,
+ color: "var(--color-text-secondary)",
+};
+
+function NodeButton({
+ id,
+ label,
+ onSelectNode,
+}: {
+ id: string;
+ label: string;
+ onSelectNode?: (id: string) => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={() => onSelectNode?.(id)}
+ title={id}
+ style={{
+ cursor: onSelectNode ? "pointer" : "default",
+ background: "transparent",
+ color: "var(--color-text-primary)",
+ fontWeight: 600,
+ padding: 0,
+ }}
+ >
+ {label}
+ </button>
+ );
+}
+
+function ViolationRow({
+ violation,
+ onSelectNode,
+}: {
+ violation: ConformanceViolation;
+ onSelectNode?: (id: string) => void;
+}) {
+ const color = "var(--color-risk-high)";
+ return (
+ <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--color-border-subtle)" }}>
+ <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
+ <span
+ style={{
+ flexShrink: 0,
+ color,
+ border: `1px solid color-mix(in srgb, ${color} 45%, transparent)`,
+ background: `color-mix(in srgb, ${color} 16%, transparent)`,
+ borderRadius: 4,
+ fontSize: 9,
+ fontWeight: 700,
+ textTransform: "uppercase",
+ padding: "1px 5px",
+ }}
+ >
+ violation
+ </span>
+ <NodeButton
+ id={violation.source}
+ label={violation.source_name || violation.source}
+ {...(onSelectNode ? { onSelectNode } : {})}
+ />
+ <span style={{ color: "var(--color-text-tertiary)" }}>→</span>
+ <NodeButton
+ id={violation.target}
+ label={violation.target_name || violation.target}
+ {...(onSelectNode ? { onSelectNode } : {})}
+ />
+ <span style={{ color: "var(--color-text-tertiary)", fontSize: 10 }}>
+ ({violation.edge_kind})
+ </span>
+ </div>
+ <div style={{ color: "var(--color-text-secondary)", marginTop: 3 }}>
+ breaks rule{" "}
+ <code style={{ color: "var(--color-warning)" }}>
+ {violation.rule_source} !-&gt; {violation.rule_target}
+ </code>
+ </div>
+ {violation.rule_description && (
+ <div style={{ color: "var(--color-text-tertiary)", fontSize: 10, marginTop: 2 }}>
+ {violation.rule_description}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function CycleRow({
+ cycle,
+ onSelectNode,
+}: {
+ cycle: DependencyCycle;
+ onSelectNode?: (id: string) => void;
+}) {
+ const color = "var(--color-warning)";
+ return (
+ <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--color-border-subtle)" }}>
+ <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
+ <span
+ style={{
+ flexShrink: 0,
+ color,
+ border: `1px solid color-mix(in srgb, ${color} 45%, transparent)`,
+ background: `color-mix(in srgb, ${color} 16%, transparent)`,
+ borderRadius: 4,
+ fontSize: 9,
+ fontWeight: 700,
+ textTransform: "uppercase",
+ padding: "1px 5px",
+ }}
+ >
+ cycle · {cycle.length}
+ </span>
+ </div>
+ <div style={{ marginTop: 4, display: "flex", flexWrap: "wrap", alignItems: "center", gap: 4 }}>
+ {cycle.nodes.map((nid, i) => (
+ <span key={nid} style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
+ <NodeButton id={nid} label={nid} {...(onSelectNode ? { onSelectNode } : {})} />
+ {i < cycle.nodes.length - 1 && (
+ <span style={{ color: "var(--color-text-tertiary)" }}>→</span>
+ )}
+ </span>
+ ))}
+ <span style={{ color: "var(--color-text-tertiary)" }}>↩</span>
+ </div>
+ </div>
+ );
+}
+
+export function SystemMapConformancePanel({
+ report,
+ loading,
+ onSelectNode,
+ onClear,
+}: SystemMapConformancePanelProps) {
+ if (!report) return null;
+
+ return (
+ <div style={panelStyle}>
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ padding: "10px 12px",
+ borderBottom: "1px solid var(--color-border-default)",
+ }}
+ >
+ <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
+ <ShieldAlert size={13} style={{ color: "var(--color-risk-high)" }} />
+ <span
+ style={{
+ fontSize: 10,
+ fontWeight: 700,
+ letterSpacing: 0.6,
+ textTransform: "uppercase",
+ color: "var(--color-text-tertiary)",
+ }}
+ >
+ Architecture conformance
+ </span>
+ </span>
+ <button
+ type="button"
+ onClick={onClear}
+ aria-label="Clear conformance"
+ style={{ cursor: "pointer", color: "var(--color-text-tertiary)", display: "inline-flex" }}
+ >
+ <X size={14} />
+ </button>
+ </div>
+
+ <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--color-border-default)" }}>
+ <div style={{ color: "var(--color-text-tertiary)", fontSize: 11 }}>
+ {loading
+ ? "Checking the latest update…"
+ : `${report.violation_count} violation(s), ${report.cycle_count} cycle(s) from ${report.rules_evaluated} rule(s)`}
+ </div>
+ </div>
+
+ {!loading && report.violations.length === 0 && report.cycles.length === 0 && (
+ <div
+ style={{
+ padding: "12px",
+ color: "var(--color-text-tertiary)",
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ }}
+ >
+ <RefreshCw size={12} />
+ {report.rules_evaluated > 0
+ ? "No rule violations or dependency cycles."
+ : "No dependency cycles. Declare conformance rules to enforce allowed dependencies."}
+ </div>
+ )}
+
+ {report.violations.map((v) => (
+ <ViolationRow
+ key={`${v.edge_id}:${v.rule_source}:${v.rule_target}`}
+ violation={v}
+ {...(onSelectNode ? { onSelectNode } : {})}
+ />
+ ))}
+ {report.cycles.map((c) => (
+ <CycleRow key={c.nodes.join("->")} cycle={c} {...(onSelectNode ? { onSelectNode } : {})} />
+ ))}
+ </div>
+ );
+}
diff --git a/packages/web/src/app/workspace/conformance/page.tsx b/packages/web/src/app/workspace/conformance/page.tsx
new file mode 100644
index 000000000..9d09d5a6c
--- /dev/null
+++ b/packages/web/src/app/workspace/conformance/page.tsx
@@ -0,0 +1,177 @@
+"use client";
+
+import { useMemo } from "react";
+import { useRouter } from "next/navigation";
+import { ShieldCheck, ShieldAlert, RefreshCw, Waypoints, ListChecks } 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";
+
+export default function ConformancePage() {
+ const router = useRouter();
+ const { data: graph, isLoading: graphLoading } = useWorkspaceSystemGraph();
+ const { data: report, isLoading: reportLoading } = useWorkspaceConformance();
+
+ const isLoading = graphLoading || reportLoading;
+ const matrix = useMemo(() => buildDsm(graph, report), [graph, report]);
+
+ const violations = report?.violations ?? [];
+ const cycles = report?.cycles ?? [];
+
+ return (
+ <div className="p-5 sm:p-8 space-y-6 max-w-[1400px]">
+ <div>
+ <div className="flex items-center gap-2.5 mb-1">
+ <ShieldCheck className="h-6 w-6 text-[var(--color-accent-primary)]" />
+ <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">
+ Architecture Conformance
+ </h1>
+ </div>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ Declared dependency rules checked against the live system graph, plus any
+ circular service dependencies. Declare rules under{" "}
+ <code className="text-[var(--color-text-primary)]">conformance:</code> in
+ your <code className="text-[var(--color-text-primary)]">.repowise-workspace.yaml</code>;
+ run <code className="text-[var(--color-text-primary)]">repowise workspace check</code> to
+ gate CI.
+ </p>
+ </div>
+
+ <div className="grid grid-cols-2 gap-3 lg:grid-cols-3">
+ <StatCard
+ label="Rules evaluated"
+ value={isLoading ? "—" : (report?.rules_evaluated ?? 0)}
+ icon={<ListChecks className="h-4 w-4 text-[var(--color-accent-secondary)]" />}
+ />
+ <StatCard
+ label="Violations"
+ value={isLoading ? "—" : violations.length}
+ description="Dependencies that break a declared rule"
+ icon={<ShieldAlert className="h-4 w-4 text-[var(--color-risk-high)]" />}
+ />
+ <StatCard
+ label="Dependency cycles"
+ value={isLoading ? "—" : cycles.length}
+ description="Circular service dependencies"
+ icon={<RefreshCw className="h-4 w-4 text-[var(--color-warning)]" />}
+ />
+ </div>
+
+ {/* DSM */}
+ <Card>
+ <CardHeader className="pb-2 flex-row items-center justify-between">
+ <CardTitle className="text-sm font-medium">
+ Dependency-structure matrix
+ </CardTitle>
+ <button
+ type="button"
+ onClick={() => router.push("/workspace/system-map")}
+ className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
+ >
+ <Waypoints className="h-3.5 w-3.5" />
+ Open System Map
+ </button>
+ </CardHeader>
+ <CardContent className="pt-0">
+ <p className="text-xs text-[var(--color-text-tertiary)] mb-3">
+ Each filled cell means the row service depends on the column service,
+ tinted by transport. Red cells break a rule; amber cells sit on a cycle.
+ </p>
+ {isLoading ? (
+ <Skeleton className="h-72 w-full" />
+ ) : (
+ <DsmMatrixView matrix={matrix} />
+ )}
+ </CardContent>
+ </Card>
+
+ {/* Governance findings */}
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium inline-flex items-center gap-2">
+ <ShieldAlert className="h-4 w-4 text-[var(--color-risk-high)]" />
+ Rule violations ({violations.length})
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0 space-y-3">
+ {isLoading ? (
+ <Skeleton className="h-20 w-full" />
+ ) : violations.length === 0 ? (
+ <p className="text-sm text-[var(--color-text-tertiary)]">
+ {report && report.rules_evaluated > 0
+ ? "No dependencies violate the declared rules."
+ : "No rules declared yet. Add a conformance block to start enforcing allowed dependencies."}
+ </p>
+ ) : (
+ violations.map((v) => (
+ <div
+ key={`${v.edge_id}:${v.rule_source}:${v.rule_target}`}
+ className="rounded-md border border-[var(--color-border-subtle)] p-3 text-sm"
+ >
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="font-semibold text-[var(--color-text-primary)]">
+ {v.source_name || v.source}
+ </span>
+ <span className="text-[var(--color-text-tertiary)]">→</span>
+ <span className="font-semibold text-[var(--color-text-primary)]">
+ {v.target_name || v.target}
+ </span>
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ ({v.edge_kind})
+ </span>
+ </div>
+ <div className="text-[var(--color-text-secondary)] mt-1">
+ breaks{" "}
+ <code className="text-[var(--color-warning)]">
+ {v.rule_source} !-&gt; {v.rule_target}
+ </code>
+ </div>
+ {v.rule_description && (
+ <div className="text-xs text-[var(--color-text-tertiary)] mt-1">
+ {v.rule_description}
+ </div>
+ )}
+ </div>
+ ))
+ )}
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium inline-flex items-center gap-2">
+ <RefreshCw className="h-4 w-4 text-[var(--color-warning)]" />
+ Dependency cycles ({cycles.length})
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0 space-y-3">
+ {isLoading ? (
+ <Skeleton className="h-20 w-full" />
+ ) : cycles.length === 0 ? (
+ <p className="text-sm text-[var(--color-text-tertiary)]">
+ No circular service dependencies detected.
+ </p>
+ ) : (
+ cycles.map((c) => (
+ <div
+ key={c.nodes.join("->")}
+ className="rounded-md border border-[var(--color-border-subtle)] p-3 text-sm"
+ >
+ <div className="text-xs uppercase tracking-wide text-[var(--color-text-tertiary)] mb-1">
+ {c.length} services
+ </div>
+ <div className="text-[var(--color-text-primary)] break-words">
+ {c.nodes.join(" → ")} → {c.nodes[0]}
+ </div>
+ </div>
+ ))
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsx
index f0abd373f..371636433 100644
--- a/packages/web/src/app/workspace/system-map/page.tsx
+++ b/packages/web/src/app/workspace/system-map/page.tsx
@@ -2,13 +2,15 @@
import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
-import { Waypoints, Boxes, ArrowLeftRight, Share2, Zap, AlertTriangle } from "lucide-react";
+import { Waypoints, Boxes, ArrowLeftRight, Share2, Zap, AlertTriangle, ShieldAlert } from "lucide-react";
import {
SystemMap,
SystemMapBlastPanel,
SystemMapBreakingPanel,
+ SystemMapConformancePanel,
buildBlastRadiusOverlay,
buildBreakingChangeOverlay,
+ buildConformanceOverlay,
type RepoHealth,
} from "@repowise-dev/ui/workspace/system-map";
import { StatCard } from "@repowise-dev/ui/shared/stat-card";
@@ -18,6 +20,7 @@ import {
useWorkspaceGraph,
useWorkspaceBlastRadius,
useWorkspaceBreakingChanges,
+ useWorkspaceConformance,
} from "@/lib/hooks/use-workspace";
export default function SystemMapPage() {
@@ -40,6 +43,12 @@ export default function SystemMapPage() {
const { data: breaking, isLoading: breakingLoading } =
useWorkspaceBreakingChanges(showBreaking);
+ // Architecture conformance. Lazy-fetched on toggle; violation/cycle badges ride
+ // the same overlay prop when no blast target or breaking-change view is active.
+ const [showConformance, setShowConformance] = useState(false);
+ const { data: conformance, isLoading: conformanceLoading } =
+ useWorkspaceConformance(showConformance);
+
// 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.
@@ -56,9 +65,10 @@ export default function SystemMapPage() {
const overlay = useMemo(() => {
if (!graph) return undefined;
if (blast) return buildBlastRadiusOverlay(graph, blast);
+ if (showConformance && conformance) return buildConformanceOverlay(graph, conformance);
if (showBreaking && breaking) return buildBreakingChangeOverlay(graph, breaking);
return undefined;
- }, [graph, blast, showBreaking, breaking]);
+ }, [graph, blast, showBreaking, breaking, showConformance, conformance]);
const diag = graph?.diagnostics;
const serviceCount = graph?.nodes.length ?? 0;
@@ -136,9 +146,31 @@ export default function SystemMapPage() {
</label>
<button
type="button"
- onClick={() => setShowBreaking((v) => !v)}
- aria-pressed={showBreaking}
+ onClick={() => {
+ setShowConformance((v) => !v);
+ if (!showConformance) setShowBreaking(false);
+ }}
+ aria-pressed={showConformance}
className={`ml-auto 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)]"
+ }`}
+ >
+ <ShieldAlert className="h-4 w-4" />
+ Conformance
+ {showConformance && conformance && conformance.violation_count > 0 && (
+ <span className="font-semibold">· {conformance.violation_count}</span>
+ )}
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ setShowBreaking((v) => !v);
+ if (!showBreaking) setShowConformance(false);
+ }}
+ aria-pressed={showBreaking}
+ className={`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-sm ${
showBreaking
? "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)]"
@@ -189,6 +221,14 @@ export default function SystemMapPage() {
onClear={() => setShowBreaking(false)}
/>
)}
+ {showConformance && (
+ <SystemMapConformancePanel
+ report={conformance}
+ loading={conformanceLoading}
+ onSelectNode={setBlastTarget}
+ onClear={() => setShowConformance(false)}
+ />
+ )}
</>
)}
</div>
diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.ts
index db07b3d41..9f421e1c0 100644
--- a/packages/web/src/components/layout/nav-items.ts
+++ b/packages/web/src/components/layout/nav-items.ts
@@ -21,6 +21,7 @@ import {
Link2,
MessageSquare,
Settings,
+ ShieldCheck,
Users,
Waypoints,
} from "lucide-react";
@@ -46,6 +47,7 @@ export const GLOBAL_NAV: NavItem[] = [
export const WORKSPACE_NAV: NavItem[] = [
{ label: "Overview", href: "/workspace", icon: Layers, exact: true },
{ label: "System Map", href: "/workspace/system-map", icon: Waypoints },
+ { label: "Conformance", href: "/workspace/conformance", icon: ShieldCheck },
{ label: "Contracts", href: "/workspace/contracts", icon: Link2 },
{ label: "Co-Changes", href: "/workspace/co-changes", icon: GitMerge },
];
diff --git a/packages/web/src/lib/api/types/workspace.ts b/packages/web/src/lib/api/types/workspace.ts
index 9a445dd68..cae0a6fc0 100644
--- a/packages/web/src/lib/api/types/workspace.ts
+++ b/packages/web/src/lib/api/types/workspace.ts
@@ -150,12 +150,19 @@ export type {
BreakingChangeConsumer,
BreakingChangeReport,
BreakingChangeSeverity,
+ ConformanceRule,
+ ConformanceViolation,
+ DependencyCycle,
+ ConformanceReport,
+ DsmCell,
+ DsmMatrix,
} from "@repowise-dev/types";
import type {
SystemGraph,
CrossRepoBlastRadius,
BreakingChangeReport,
+ ConformanceReport,
} from "@repowise-dev/types";
/** `GET /api/workspace/system-graph` — the full service-granular system graph. */
@@ -166,3 +173,6 @@ export type WorkspaceBlastRadiusResponse = CrossRepoBlastRadius;
/** `GET /api/workspace/breaking-changes` — incompatible provider changes + impact. */
export type WorkspaceBreakingChangesResponse = BreakingChangeReport;
+
+/** `GET /api/workspace/conformance` — architecture rule violations + cycles. */
+export type WorkspaceConformanceResponse = ConformanceReport;
diff --git a/packages/web/src/lib/api/workspace.ts b/packages/web/src/lib/api/workspace.ts
index 101334ac9..b85a65a71 100644
--- a/packages/web/src/lib/api/workspace.ts
+++ b/packages/web/src/lib/api/workspace.ts
@@ -8,6 +8,7 @@ import type {
WorkspaceSystemGraphResponse,
WorkspaceBlastRadiusResponse,
WorkspaceBreakingChangesResponse,
+ WorkspaceConformanceResponse,
} from "./types";
export async function getWorkspace(
@@ -94,6 +95,19 @@ export async function getWorkspaceBreakingChanges(opts?: {
return apiGet<WorkspaceBreakingChangesResponse>("/api/workspace/breaking-changes", params);
}
+/**
+ * Architecture conformance from the most recent update: dependency-rule
+ * violations + dependency cycles over the system graph. Optionally filter to
+ * findings involving one repo.
+ */
+export async function getWorkspaceConformance(opts?: {
+ repo?: string;
+}): Promise<WorkspaceConformanceResponse> {
+ const params: Record<string, string> = {};
+ if (opts?.repo) params.repo = opts.repo;
+ return apiGet<WorkspaceConformanceResponse>("/api/workspace/conformance", params);
+}
+
/**
* 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 1c6cc7a25..bbc46b8c3 100644
--- a/packages/web/src/lib/hooks/use-workspace.ts
+++ b/packages/web/src/lib/hooks/use-workspace.ts
@@ -9,6 +9,7 @@ import {
getWorkspaceGraph,
getWorkspaceBlastRadius,
getWorkspaceBreakingChanges,
+ getWorkspaceConformance,
} from "@/lib/api/workspace";
import type {
WorkspaceResponse,
@@ -18,6 +19,7 @@ import type {
WorkspaceGraphResponse,
WorkspaceBlastRadiusResponse,
WorkspaceBreakingChangesResponse,
+ WorkspaceConformanceResponse,
} from "@/lib/api/types";
export function useWorkspace() {
@@ -108,6 +110,19 @@ export function useWorkspaceBreakingChanges(enabled = true) {
return { data: data ?? null, isLoading, error };
}
+/**
+ * Architecture conformance report from the most recent workspace update. Pass
+ * ``enabled=false`` to skip the request until the view needs it.
+ */
+export function useWorkspaceConformance(enabled = true) {
+ const { data, error, isLoading } = useSWR<WorkspaceConformanceResponse>(
+ enabled ? "workspace:conformance" : null,
+ () => getWorkspaceConformance(),
+ { 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/cli/test_workspace_cmd.py b/tests/unit/cli/test_workspace_cmd.py
index 55103a381..a618e55c8 100644
--- a/tests/unit/cli/test_workspace_cmd.py
+++ b/tests/unit/cli/test_workspace_cmd.py
@@ -522,3 +522,91 @@ class TestWorkspaceDiagnostics:
result = runner.invoke(cli, ["workspace", "diagnostics", "--help"])
assert result.exit_code == 0
assert "--json" in result.output
+
+
+# ---------------------------------------------------------------------------
+# workspace check
+# ---------------------------------------------------------------------------
+
+
+class TestWorkspaceCheck:
+ def _write_config_with_rule(self, root: Path, rules: list[dict]) -> None:
+ data = {
+ "version": 1,
+ "default_repo": "frontend",
+ "repos": [
+ {"path": "frontend", "alias": "frontend"},
+ {"path": "db", "alias": "db"},
+ ],
+ "conformance": {"rules": rules},
+ }
+ (root / WORKSPACE_CONFIG_FILENAME).write_text(
+ yaml.dump(data, default_flow_style=False), encoding="utf-8"
+ )
+
+ def _save_graph(self, root: Path, edges: list[tuple[str, str]]) -> None:
+ from repowise.core.workspace.system_graph import (
+ SystemEdge,
+ SystemGraph,
+ SystemNode,
+ save_system_graph,
+ )
+
+ node_ids = {n for e in edges for n in e}
+ graph = SystemGraph(
+ nodes=[SystemNode(id=n, repo=n, service_path=None, name=n) for n in sorted(node_ids)],
+ edges=[
+ SystemEdge(
+ id=f"{s}->{t}:http",
+ source=s,
+ target=t,
+ kind="http",
+ match_type="exact",
+ confidence=1.0,
+ weight=1,
+ structural=True,
+ )
+ for s, t in edges
+ ],
+ )
+ save_system_graph(graph, root)
+
+ def test_check_reports_violation_and_cycle(self, runner, tmp_path):
+ self._write_config_with_rule(tmp_path, [{"source": "frontend", "target": "db"}])
+ # frontend -> db (violation) and db -> frontend (forms a cycle)
+ self._save_graph(tmp_path, [("frontend", "db"), ("db", "frontend")])
+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path)])
+ assert result.exit_code == 1, result.output
+ assert "violation" in result.output.lower()
+ assert "cycle" in result.output.lower()
+ assert "frontend !-> db" in result.output
+
+ def test_check_clean_passes(self, runner, tmp_path):
+ self._write_config_with_rule(tmp_path, [{"source": "frontend", "target": "db"}])
+ # frontend never depends on db directly, and the graph is acyclic
+ (tmp_path / "api").mkdir(exist_ok=True)
+ self._save_graph(tmp_path, [("frontend", "api"), ("api", "db")])
+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path)])
+ assert result.exit_code == 0, result.output
+ assert "No violations" in result.output
+
+ def test_check_json_exit_code(self, runner, tmp_path):
+ import json
+
+ self._write_config_with_rule(tmp_path, [{"source": "frontend", "target": "db"}])
+ self._save_graph(tmp_path, [("frontend", "db")])
+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path), "--json"])
+ assert result.exit_code == 1
+ data = json.loads(result.output)
+ assert data["violation_count"] == 1
+
+ def test_check_missing_graph(self, runner, tmp_path):
+ self._write_config_with_rule(tmp_path, [])
+ result = runner.invoke(cli, ["workspace", "check", str(tmp_path)])
+ assert result.exit_code != 0
+ assert "No system graph found" in result.output
+
+ def test_check_help(self, runner):
+ result = runner.invoke(cli, ["workspace", "check", "--help"])
+ assert result.exit_code == 0
+ assert "non-zero" in result.output or "CI" in result.output
diff --git a/tests/unit/server/test_mcp_conformance.py b/tests/unit/server/test_mcp_conformance.py
new file mode 100644
index 000000000..e82d60b3a
--- /dev/null
+++ b/tests/unit/server/test_mcp_conformance.py
@@ -0,0 +1,164 @@
+"""Tests for the get_conformance MCP tool + the get_risk conformance directive."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.core.workspace.config import ConformanceRule
+from repowise.core.workspace.conformance import build_conformance_report
+from repowise.core.workspace.system_graph import SystemEdge, SystemGraph, SystemNode
+from repowise.server.mcp_server import _state
+from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+from repowise.server.mcp_server.tool_conformance import get_conformance
+
+
+def _graph() -> SystemGraph:
+ return SystemGraph(
+ nodes=[
+ SystemNode(id="frontend", repo="frontend", service_path=None, name="frontend"),
+ SystemNode(id="db", repo="db", service_path=None, name="db"),
+ ],
+ edges=[
+ SystemEdge(
+ id="frontend->db:http",
+ source="frontend",
+ target="db",
+ kind="http",
+ match_type="exact",
+ confidence=1.0,
+ weight=1,
+ structural=True,
+ ),
+ SystemEdge(
+ id="db->frontend:http",
+ source="db",
+ target="frontend",
+ kind="http",
+ match_type="exact",
+ confidence=1.0,
+ weight=1,
+ structural=True,
+ ),
+ ],
+ )
+
+
+def _enricher_with_conformance(tmp_path: Path) -> CrossRepoEnricher:
+ report = build_conformance_report(
+ _graph(), [ConformanceRule(source="frontend", target="db")], generated_at="t"
+ )
+ (tmp_path / "conformance.json").write_text(json.dumps(report.to_dict()), encoding="utf-8")
+ return CrossRepoEnricher(
+ tmp_path / "cross_repo_edges.json",
+ conformance_path=tmp_path / "conformance.json",
+ )
+
+
+def workspace_state(tmp_path: Path):
+ prev_registry = _state._registry
+ prev_enricher = _state._cross_repo_enricher
+ _state._registry = object()
+ _state._cross_repo_enricher = _enricher_with_conformance(tmp_path)
+ try:
+ yield
+ finally:
+ _state._registry = prev_registry
+ _state._cross_repo_enricher = prev_enricher
+
+
+async def test_requires_workspace_mode():
+ prev = _state._registry
+ _state._registry = None
+ try:
+ result = await get_conformance()
+ finally:
+ _state._registry = prev
+ assert "error" in result
+ assert "workspace mode" in result["error"]
+
+
+async def test_reports_violations_and_cycles(workspace_state):
+ result = await get_conformance()
+ assert result["violation_count"] == 1
+ assert result["cycle_count"] == 1
+ assert result["violations"][0]["source"] == "frontend"
+ assert "violation" in result["summary"]
+
+
+async def test_filter_by_repo(workspace_state):
+ result = await get_conformance(repo="unrelated")
+ assert result["violation_count"] == 0
+ assert result["cycle_count"] == 0
+
+
+async def test_no_report_returns_error(tmp_path: Path):
+ prev_registry = _state._registry
+ prev_enricher = _state._cross_repo_enricher
+ _state._registry = object()
+ _state._cross_repo_enricher = CrossRepoEnricher(tmp_path / "cross_repo_edges.json")
+ try:
+ result = await get_conformance()
+ finally:
+ _state._registry = prev_registry
+ _state._cross_repo_enricher = prev_enricher
+ assert "error" in result
+ assert "conformance" in result["error"].lower()
+
+
+# ---------------------------------------------------------------------------
+# get_risk PR-mode conformance directive
+# ---------------------------------------------------------------------------
+
+
+def test_conformance_directive_reports_repo_findings(tmp_path: Path):
+ from repowise.server.mcp_server.tool_risk import _conformance_directive
+
+ prev_registry = _state._registry
+ prev_enricher = _state._cross_repo_enricher
+ _state._registry = object()
+ _state._cross_repo_enricher = _enricher_with_conformance(tmp_path)
+ try:
+ violations, cycles = _conformance_directive("frontend")
+ finally:
+ _state._registry = prev_registry
+ _state._cross_repo_enricher = prev_enricher
+ assert len(violations) == 1
+ assert violations[0]["source"] == "frontend"
+ assert violations[0]["rule"] == "frontend !-> db"
+ # frontend participates in the frontend<->db cycle.
+ assert len(cycles) == 1
+
+
+def test_conformance_directive_empty_for_unrelated_repo(tmp_path: Path):
+ from repowise.server.mcp_server.tool_risk import _conformance_directive
+
+ prev_registry = _state._registry
+ prev_enricher = _state._cross_repo_enricher
+ _state._registry = object()
+ _state._cross_repo_enricher = _enricher_with_conformance(tmp_path)
+ try:
+ violations, cycles = _conformance_directive("unrelated")
+ finally:
+ _state._registry = prev_registry
+ _state._cross_repo_enricher = prev_enricher
+ assert violations == []
+ assert cycles == []
+
+
+def test_conformance_directive_empty_outside_workspace():
+ from repowise.server.mcp_server.tool_risk import _conformance_directive
+
+ prev = _state._registry
+ _state._registry = None
+ try:
+ assert _conformance_directive("frontend") == ([], [])
+ finally:
+ _state._registry = prev
diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.py
index a33c2eb78..ee0cbac0a 100644
--- a/tests/unit/server/test_workspace_router.py
+++ b/tests/unit/server/test_workspace_router.py
@@ -849,3 +849,107 @@ class TestGetBreakingChanges:
assert data["changes"] == []
assert data["total"] == 0
assert data["impacted_repos"] == []
+
+
+# ---------------------------------------------------------------------------
+# GET /api/workspace/conformance
+# ---------------------------------------------------------------------------
+
+
+def _make_conformance_enricher(tmp_path: Path) -> CrossRepoEnricher:
+ """Enricher backed by a real, core-built conformance report artifact."""
+ from repowise.core.workspace.config import ConformanceRule
+ from repowise.core.workspace.conformance import build_conformance_report
+ from repowise.core.workspace.system_graph import SystemEdge, SystemGraph, SystemNode
+
+ graph = SystemGraph(
+ nodes=[
+ SystemNode(id="frontend", repo="frontend", service_path=None, name="frontend"),
+ SystemNode(id="db", repo="db", service_path=None, name="db"),
+ ],
+ edges=[
+ SystemEdge(
+ id="frontend->db:http",
+ source="frontend",
+ target="db",
+ kind="http",
+ match_type="exact",
+ confidence=1.0,
+ weight=1,
+ structural=True,
+ ),
+ SystemEdge(
+ id="db->frontend:http",
+ source="db",
+ target="frontend",
+ kind="http",
+ match_type="exact",
+ confidence=1.0,
+ weight=1,
+ structural=True,
+ ),
+ ],
+ )
+ report = build_conformance_report(
+ graph, [ConformanceRule(source="frontend", target="db")], generated_at="t"
+ )
+ _write_json(tmp_path / "conformance.json", report.to_dict())
+ return CrossRepoEnricher(
+ tmp_path / "cross_repo_edges.json",
+ conformance_path=tmp_path / "conformance.json",
+ )
+
+
+class TestGetConformance:
+ @pytest.mark.asyncio
+ async def test_not_workspace_mode(self) -> None:
+ app = _make_workspace_app()
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/conformance")
+ assert resp.status_code == 404
+
+ @pytest.mark.asyncio
+ async def test_empty_when_no_report(self) -> None:
+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=None)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/conformance")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["violations"] == []
+ assert body["cycles"] == []
+
+ @pytest.mark.asyncio
+ async def test_reports_violation_and_cycle(self, tmp_path: Path) -> None:
+ enricher = _make_conformance_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/conformance")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["violation_count"] == 1
+ assert data["cycle_count"] == 1
+ assert data["violations"][0]["source"] == "frontend"
+ assert data["violations"][0]["target"] == "db"
+ assert set(data["violating_repos"]) == {"frontend", "db"}
+
+ @pytest.mark.asyncio
+ async def test_filter_by_repo(self, tmp_path: Path) -> None:
+ enricher = _make_conformance_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=_make_ws_config(), enricher=enricher)
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/conformance", params={"repo": "frontend"})
+ assert resp.status_code == 200
+ data = resp.json()
+ # frontend participates in both the violation and the cycle
+ assert data["violation_count"] == 1
+ assert data["cycle_count"] == 1
+
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/conformance", params={"repo": "unrelated"})
+ data = resp.json()
+ assert data["violation_count"] == 0
+ assert data["cycle_count"] == 0
diff --git a/tests/unit/workspace/test_conformance.py b/tests/unit/workspace/test_conformance.py
new file mode 100644
index 000000000..686e31aaa
--- /dev/null
+++ b/tests/unit/workspace/test_conformance.py
@@ -0,0 +1,314 @@
+"""Tests for architecture conformance — matchers, rule checking, cycles, IO.
+
+The negative cases are load-bearing: a clean graph must produce no violations,
+a behavioral co-change edge must never count as a dependency, and an ``allow``
+exception must suppress an otherwise-denied edge.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.workspace.config import (
+ ConformanceConfig,
+ ConformanceRule,
+ RepoEntry,
+ WorkspaceConfig,
+)
+from repowise.core.workspace.conformance import (
+ CONFORMANCE_FILENAME,
+ ConformanceReport,
+ build_conformance_report,
+ check_conformance,
+ compile_matcher,
+ load_conformance_report,
+ run_conformance_check,
+ save_conformance_report,
+ tags_by_repo_from_config,
+)
+from repowise.core.workspace.cycles import detect_cycles
+from repowise.core.workspace.system_graph import SystemEdge, SystemGraph, SystemNode
+
+# ---------------------------------------------------------------------------
+# Fixture builders
+# ---------------------------------------------------------------------------
+
+
+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=nodes, edges=edges)
+
+
+# ---------------------------------------------------------------------------
+# Matchers
+# ---------------------------------------------------------------------------
+
+
+def test_wildcard_matcher_matches_any():
+ pred = compile_matcher("*")
+ assert pred(_node("frontend"), {}) is True
+ assert pred(_node("db"), {}) is True
+
+
+def test_tag_matcher_matches_repo_tag():
+ pred = compile_matcher("tag:edge")
+ tags = {"frontend": ["edge", "ui"], "db": []}
+ assert pred(_node("frontend"), tags) is True
+ assert pred(_node("db"), tags) is False
+
+
+def test_glob_matcher_matches_id_repo_and_name():
+ # bare alias matches the repo
+ assert compile_matcher("frontend")(_node("frontend"), {}) is True
+ # glob over a service node id
+ svc = _node("api::services/auth", repo="api", name="auth", service_path="services/auth")
+ assert compile_matcher("api::*")(svc, {}) is True
+ # name match
+ assert compile_matcher("auth")(svc, {}) is True
+ # non-match
+ assert compile_matcher("payments")(_node("frontend"), {}) is False
+
+
+# ---------------------------------------------------------------------------
+# Rule checking — violation + clean
+# ---------------------------------------------------------------------------
+
+
+def test_deny_rule_flags_violating_dependency():
+ g = _graph(
+ [_node("frontend"), _node("db")],
+ [_edge("frontend", "db")],
+ )
+ violations = check_conformance(g, [ConformanceRule(source="frontend", target="db")])
+ assert len(violations) == 1
+ v = violations[0]
+ assert v.source == "frontend"
+ assert v.target == "db"
+ assert v.edge_kind == "http"
+ assert v.rule_source == "frontend"
+ assert v.rule_target == "db"
+
+
+def test_clean_graph_has_no_violations():
+ g = _graph(
+ [_node("frontend"), _node("api"), _node("db")],
+ [_edge("frontend", "api"), _edge("api", "db")],
+ )
+ # frontend must not talk to db directly; it doesn't (only api -> db).
+ violations = check_conformance(g, [ConformanceRule(source="frontend", target="db")])
+ assert violations == []
+
+
+def test_wildcard_deny_rule():
+ g = _graph(
+ [_node("frontend"), _node("api"), _node("legacy")],
+ [_edge("frontend", "legacy"), _edge("api", "legacy")],
+ )
+ violations = check_conformance(g, [ConformanceRule(source="*", target="legacy")])
+ assert {v.source for v in violations} == {"frontend", "api"}
+
+
+def test_allow_rule_whitelists_exception():
+ g = _graph(
+ [_node("frontend"), _node("migrations"), _node("db")],
+ [_edge("frontend", "db"), _edge("migrations", "db")],
+ )
+ rules = [
+ ConformanceRule(source="*", target="db"), # deny all -> db
+ ConformanceRule(source="migrations", target="db", allow=True), # except migrations
+ ]
+ violations = check_conformance(g, rules)
+ assert [v.source for v in violations] == ["frontend"]
+
+
+def test_behavioral_edge_is_never_a_violation():
+ g = _graph(
+ [_node("frontend"), _node("db")],
+ [_edge("frontend", "db", kind="co_change", structural=False)],
+ )
+ violations = check_conformance(g, [ConformanceRule(source="frontend", target="db")])
+ assert violations == []
+
+
+def test_tag_based_rule():
+ g = _graph(
+ [_node("frontend"), _node("admin"), _node("db")],
+ [_edge("frontend", "db"), _edge("admin", "db")],
+ )
+ tags = {"frontend": ["ui"], "admin": ["ui"], "db": ["data"]}
+ violations = check_conformance(g, [ConformanceRule(source="tag:ui", target="tag:data")], tags)
+ assert {v.source for v in violations} == {"frontend", "admin"}
+
+
+def test_no_deny_rules_yields_no_violations():
+ g = _graph([_node("a"), _node("b")], [_edge("a", "b")])
+ # only an allow rule present
+ assert check_conformance(g, [ConformanceRule(source="a", target="b", allow=True)]) == []
+
+
+# ---------------------------------------------------------------------------
+# Cycle detection
+# ---------------------------------------------------------------------------
+
+
+def test_two_node_cycle():
+ g = _graph(
+ [_node("a"), _node("b")],
+ [_edge("a", "b"), _edge("b", "a")],
+ )
+ cycles = detect_cycles(g)
+ assert len(cycles) == 1
+ assert set(cycles[0].nodes) == {"a", "b"}
+ assert len(cycles[0].edge_ids) == 2
+
+
+def test_longer_cycle():
+ g = _graph(
+ [_node("a"), _node("b"), _node("c")],
+ [_edge("a", "b"), _edge("b", "c"), _edge("c", "a")],
+ )
+ cycles = detect_cycles(g)
+ assert len(cycles) == 1
+ assert set(cycles[0].nodes) == {"a", "b", "c"}
+ assert cycles[0].length == 3
+
+
+def test_acyclic_graph_has_no_cycles():
+ g = _graph(
+ [_node("a"), _node("b"), _node("c")],
+ [_edge("a", "b"), _edge("b", "c")],
+ )
+ assert detect_cycles(g) == []
+
+
+def test_cycles_ignore_behavioral_edges():
+ # a->b structural, b->a only via co-change → not a real cycle
+ g = _graph(
+ [_node("a"), _node("b")],
+ [_edge("a", "b"), _edge("b", "a", kind="co_change", structural=False)],
+ )
+ assert detect_cycles(g) == []
+
+
+# ---------------------------------------------------------------------------
+# Report assembly
+# ---------------------------------------------------------------------------
+
+
+def test_build_report_combines_violations_and_cycles():
+ g = _graph(
+ [_node("frontend"), _node("db")],
+ [_edge("frontend", "db"), _edge("db", "frontend")],
+ )
+ report = build_conformance_report(g, [ConformanceRule(source="frontend", target="db")])
+ assert report.to_dict()["violation_count"] == 1
+ assert len(report.violations) == 1
+ assert len(report.cycles) == 1
+ assert report.rules_evaluated == 1
+ assert report.has_findings
+ assert set(report.violating_repos) == {"frontend", "db"}
+
+
+def test_report_to_dict_round_trip():
+ g = _graph([_node("a"), _node("b")], [_edge("a", "b"), _edge("b", "a")])
+ report = build_conformance_report(g, [ConformanceRule(source="a", target="b")])
+ restored = ConformanceReport.from_dict(report.to_dict())
+ assert len(restored.violations) == len(report.violations)
+ assert len(restored.cycles) == len(report.cycles)
+ assert restored.rules_evaluated == report.rules_evaluated
+
+
+# ---------------------------------------------------------------------------
+# Config parsing
+# ---------------------------------------------------------------------------
+
+
+def test_config_round_trips_rules_and_tags():
+ cfg = WorkspaceConfig(
+ repos=[
+ RepoEntry(path="fe", alias="frontend", tags=["ui", "edge"]),
+ RepoEntry(path="db", alias="db"),
+ ],
+ conformance=ConformanceConfig(
+ rules=[
+ ConformanceRule(source="frontend", target="db", description="no direct db"),
+ ConformanceRule(source="migrations", target="db", allow=True),
+ ]
+ ),
+ )
+ restored = WorkspaceConfig.from_dict(cfg.to_dict())
+ assert restored.repos[0].tags == ["ui", "edge"]
+ assert len(restored.conformance.rules) == 2
+ r0 = restored.conformance.rules[0]
+ assert r0.source == "frontend" and r0.target == "db" and r0.allow is False
+ assert r0.description == "no direct db"
+ assert restored.conformance.rules[1].allow is True
+
+
+def test_config_omits_empty_conformance():
+ cfg = WorkspaceConfig(repos=[RepoEntry(path="a", alias="a")])
+ assert "conformance" not in cfg.to_dict()
+
+
+def test_tags_by_repo_from_config():
+ cfg = WorkspaceConfig(
+ repos=[
+ RepoEntry(path="fe", alias="frontend", tags=["ui"]),
+ RepoEntry(path="db", alias="db"),
+ ]
+ )
+ assert tags_by_repo_from_config(cfg) == {"frontend": ["ui"], "db": []}
+
+
+# ---------------------------------------------------------------------------
+# Persistence + orchestrator
+# ---------------------------------------------------------------------------
+
+
+def test_save_and_load_report(tmp_path: Path):
+ g = _graph([_node("a"), _node("b")], [_edge("a", "b"), _edge("b", "a")])
+ report = build_conformance_report(g, [ConformanceRule(source="a", target="b")])
+ out = save_conformance_report(report, tmp_path)
+ assert out.name == CONFORMANCE_FILENAME
+ loaded = load_conformance_report(tmp_path)
+ assert loaded is not None
+ assert len(loaded.violations) == 1
+ assert len(loaded.cycles) == 1
+
+
+def test_load_missing_report_returns_none(tmp_path: Path):
+ assert load_conformance_report(tmp_path) is None
+
+
+def test_run_conformance_check_persists(tmp_path: Path):
+ cfg = WorkspaceConfig(
+ repos=[RepoEntry(path="fe", alias="frontend"), RepoEntry(path="db", alias="db")],
+ conformance=ConformanceConfig(rules=[ConformanceRule(source="frontend", target="db")]),
+ )
+ g = _graph([_node("frontend"), _node("db")], [_edge("frontend", "db")])
+ report = run_conformance_check(cfg, tmp_path, g)
+ assert len(report.violations) == 1
+ # persisted
+ loaded = load_conformance_report(tmp_path)
+ assert loaded is not None and len(loaded.violations) == 1