Skip to content

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

feat(workspace): detect socket contracts (#710)

joptimus149fee588535
diff --git a/packages/core/src/repowise/core/workspace/config.py b/packages/core/src/repowise/core/workspace/config.py
index a09f46725..958b7d9b4 100644
--- a/packages/core/src/repowise/core/workspace/config.py
+++ b/packages/core/src/repowise/core/workspace/config.py
@@ -72,7 +72,7 @@ class ManualContractLink:
from_repo: str
to_repo: str
- contract_type: str # "http" | "grpc" | "topic" | "data"
+ contract_type: str # "http" | "grpc" | "socket" | "topic" | "data"
contract_id: str # normalized contract ID
from_role: str = "consumer" # the from_repo's role
@@ -102,6 +102,7 @@ class ContractConfig:
detect_http: bool = True
detect_grpc: bool = True
+ detect_socket: bool = True
detect_topics: bool = True
detect_data: bool = True
manual_links: list[ManualContractLink] = field(default_factory=list)
@@ -118,6 +119,7 @@ class ContractConfig:
d: dict[str, Any] = {
"detect_http": self.detect_http,
"detect_grpc": self.detect_grpc,
+ "detect_socket": self.detect_socket,
"detect_topics": self.detect_topics,
"detect_data": self.detect_data,
}
@@ -135,6 +137,7 @@ class ContractConfig:
return cls(
detect_http=bool(data.get("detect_http", True)),
detect_grpc=bool(data.get("detect_grpc", True)),
+ detect_socket=bool(data.get("detect_socket", True)),
detect_topics=bool(data.get("detect_topics", True)),
detect_data=bool(data.get("detect_data", True)),
manual_links=manual,
@@ -234,6 +237,7 @@ class WorkspaceConfig:
[
self.contracts.detect_http,
self.contracts.detect_grpc,
+ self.contracts.detect_socket,
self.contracts.detect_topics,
self.contracts.detect_data,
]
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.py
index 97968ab6c..618415cc4 100644
--- a/packages/core/src/repowise/core/workspace/contracts.py
+++ b/packages/core/src/repowise/core/workspace/contracts.py
@@ -1,4 +1,4 @@
-"""Contract extraction: HTTP routes, gRPC services, message topics, database tables.
+"""Contract extraction: HTTP routes, gRPC services, sockets, message topics, database tables.
Write path: runs during ``repowise update --workspace``.
Results read by ``CrossRepoEnricher`` in the MCP server (read path).
@@ -46,7 +46,7 @@ class Contract:
repo: str # repo alias
contract_id: str # e.g. "http::GET::/api/users/{param}", "data::orders"
- contract_type: str # "http" | "grpc" | "topic" | "data"
+ contract_type: str # "http" | "grpc" | "socket" | "topic" | "data"
role: str # "provider" | "consumer"
file_path: str # relative to repo root
symbol_name: str # handler name, service.method, etc.
@@ -91,7 +91,7 @@ class ContractLink:
"""A matched provider↔consumer pair across repos."""
contract_id: str
- contract_type: str # "http" | "grpc" | "topic" | "data"
+ contract_type: str # "http" | "grpc" | "socket" | "topic" | "data"
match_type: str # "exact" | "candidate" | "manual"
confidence: float
provider_repo: str
@@ -166,6 +166,7 @@ def normalize_contract_id(contract_id: str) -> str:
- ``http::GET::/Api/Users/`` → ``http::GET::/api/users``
- ``grpc::PKG.Service/Method`` → ``grpc::pkg.service/Method``
+ - ``socket::/Game/State/`` → ``socket::/game/state``
- ``topic::Orders`` → ``topic::orders``
- ``data::Orders`` → ``data::orders`` (via the lowercase fallback; table
quoting/schema rules are applied at extraction time in
@@ -194,6 +195,12 @@ def normalize_contract_id(contract_id: str) -> str:
return f"grpc::{prefix}{method}"
return f"grpc::{value.lower()}"
+ if ctype == "socket" and len(parts) == 2:
+ path = parts[1].lower().rstrip("/")
+ if not path:
+ path = "/"
+ return f"socket::{path}"
+
if ctype == "topic" and len(parts) == 2:
return f"topic::{parts[1].lower()}"
@@ -683,6 +690,7 @@ async def run_contract_extraction(
DataExtractor,
GrpcExtractor,
HttpExtractor,
+ SocketExtractor,
TopicExtractor,
assign_service,
detect_service_boundaries,
@@ -717,6 +725,8 @@ async def run_contract_extraction(
extractors.append(HttpExtractor())
if contract_config.detect_grpc:
extractors.append(GrpcExtractor())
+ if contract_config.detect_socket:
+ extractors.append(SocketExtractor())
if contract_config.detect_topics:
extractors.append(TopicExtractor())
if contract_config.detect_data:
diff --git a/packages/core/src/repowise/core/workspace/extractors/__init__.py b/packages/core/src/repowise/core/workspace/extractors/__init__.py
index 145fa2a02..9cdb9a3b1 100644
--- a/packages/core/src/repowise/core/workspace/extractors/__init__.py
+++ b/packages/core/src/repowise/core/workspace/extractors/__init__.py
@@ -1,5 +1,5 @@
-"""Contract extractors: HTTP routes, gRPC services, message topics, database
-tables, service boundaries."""
+"""Contract extractors: HTTP routes, gRPC services, sockets, message topics,
+database tables, service boundaries."""
from __future__ import annotations
@@ -11,6 +11,7 @@ from .service_boundary import (
assign_service,
detect_service_boundaries,
)
+from .socket_extractor import SocketExtractor
from .topic_extractor import TopicExtractor
__all__ = [
@@ -18,6 +19,7 @@ __all__ = [
"GrpcExtractor",
"HttpExtractor",
"ServiceBoundary",
+ "SocketExtractor",
"TopicExtractor",
"assign_service",
"detect_service_boundaries",
diff --git a/packages/core/src/repowise/core/workspace/extractors/socket_extractor.py b/packages/core/src/repowise/core/workspace/extractors/socket_extractor.py
new file mode 100644
index 000000000..48c7469e6
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/socket_extractor.py
@@ -0,0 +1,188 @@
+"""Socket / websocket contract extraction.
+
+Scans source files for common websocket-style consumer and provider patterns,
+with an initial focus on Unity / C# clients and path-based server endpoints.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from .base import iter_source_files
+from .http.paths import (
+ extract_path_from_url,
+ is_unusable_consumer_path,
+ normalize_http_path,
+ strip_leading_base_expr,
+)
+from .langs import CSHARP, PYTHON
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+ from repowise.core.workspace.contracts import Contract
+
+_log = logging.getLogger("repowise.workspace.extractors.socket")
+
+_EXTENSIONS = CSHARP | PYTHON
+
+_STR = r"""(\$?@?)"([^"]*)\""""
+
+
+@dataclass(frozen=True)
+class _PatternDef:
+ regex: re.Pattern[str]
+ role: str
+ transport: str
+ confidence: float
+ label: str
+ identity_group: int
+ prefix_group: int | None = None
+ context_regex: re.Pattern[str] | None = None
+
+
+_SIGNALR_CLIENT_CONTEXT_RE = re.compile(
+ r"\bHubConnectionBuilder\b|SignalR\.Client|Microsoft\.AspNetCore\.SignalR\.Client"
+)
+
+_NATIVE_WS_CONTEXT_RE = re.compile(r"\bNativeWebSocket\b")
+_WEBSOCKETSHARP_CONTEXT_RE = re.compile(r"\bWebSocketSharp\b")
+
+_CLIENT_PATTERNS: list[_PatternDef] = [
+ _PatternDef(
+ regex=re.compile(
+ rf"""\bConnectAsync\s*\(\s*new\s+Uri\s*\(\s*{_STR}\s*\)""",
+ re.IGNORECASE,
+ ),
+ role="consumer",
+ transport="clientwebsocket",
+ confidence=0.75,
+ label="ClientWebSocket.ConnectAsync",
+ prefix_group=1,
+ identity_group=2,
+ ),
+ _PatternDef(
+ regex=re.compile(rf"""\bWithUrl\s*\(\s*{_STR}""", re.IGNORECASE),
+ role="consumer",
+ transport="signalr",
+ confidence=0.8,
+ label="HubConnectionBuilder.WithUrl",
+ prefix_group=1,
+ identity_group=2,
+ context_regex=_SIGNALR_CLIENT_CONTEXT_RE,
+ ),
+ _PatternDef(
+ regex=re.compile(rf"""\bnew\s+WebSocket\s*\(\s*{_STR}""", re.IGNORECASE),
+ role="consumer",
+ transport="nativewebsocket",
+ confidence=0.75,
+ label="NativeWebSocket.WebSocket",
+ prefix_group=1,
+ identity_group=2,
+ context_regex=_NATIVE_WS_CONTEXT_RE,
+ ),
+ _PatternDef(
+ regex=re.compile(rf"""\bnew\s+(?:\w+\.)?WebSocket\s*\(\s*{_STR}""", re.IGNORECASE),
+ role="consumer",
+ transport="websocketsharp",
+ confidence=0.75,
+ label="WebSocketSharp.WebSocket",
+ prefix_group=1,
+ identity_group=2,
+ context_regex=_WEBSOCKETSHARP_CONTEXT_RE,
+ ),
+]
+
+_PROVIDER_PATTERNS: list[_PatternDef] = [
+ _PatternDef(
+ regex=re.compile(rf"""\.\s*MapHub\s*<\s*\w+\s*>\s*\(\s*{_STR}""", re.IGNORECASE),
+ role="provider",
+ transport="signalr",
+ confidence=0.85,
+ label="MapHub",
+ prefix_group=1,
+ identity_group=2,
+ ),
+ _PatternDef(
+ regex=re.compile(r"""@(?:app|router)\.websocket\s*\(\s*['"]([^'"]+)['"]""", re.IGNORECASE),
+ role="provider",
+ transport="fastapi-websocket",
+ confidence=0.8,
+ label="@app.websocket",
+ identity_group=1,
+ ),
+]
+
+
+def _to_template(prefix: str, text: str) -> str:
+ """Rewrite a C# interpolated string body into ``${expr}`` template form."""
+ if "$" in prefix:
+ return text.replace("{", "${")
+ return text
+
+
+def _normalize_socket_identity(raw: str, prefix: str = "") -> str | None:
+ """Extract the stable path/channel identity from a socket URL-like string."""
+ value = _to_template(prefix, raw).strip()
+ if not value or "/" not in value:
+ return None
+ path = extract_path_from_url(value)
+ path, _base_token = strip_leading_base_expr(path)
+ norm = normalize_http_path(path)
+ if norm in ("", "/") or is_unusable_consumer_path(norm):
+ return None
+ return norm
+
+
+class SocketExtractor:
+ """Extract socket/websocket contracts from source files."""
+
+ def extract(
+ self,
+ repo_path: Path,
+ repo_alias: str = "",
+ exclude: Callable[[str], bool] | None = None,
+ ) -> list[Contract]:
+ from repowise.core.workspace.contracts import Contract
+
+ contracts: list[Contract] = []
+ seen: set[tuple[str, str, str]] = set()
+
+ for rel_path, _suffix, content in iter_source_files(repo_path, _EXTENSIONS, exclude):
+ for pdef in _CLIENT_PATTERNS + _PROVIDER_PATTERNS:
+ if pdef.context_regex is not None and not pdef.context_regex.search(content):
+ continue
+ for match in pdef.regex.finditer(content):
+ prefix = match.group(pdef.prefix_group) if pdef.prefix_group else ""
+ identity = _normalize_socket_identity(
+ match.group(pdef.identity_group),
+ prefix,
+ )
+ if identity is None:
+ continue
+ contract_id = f"socket::{identity}"
+ dedup_key = (rel_path, contract_id, pdef.role)
+ if dedup_key in seen:
+ continue
+ seen.add(dedup_key)
+ contracts.append(
+ Contract(
+ repo=repo_alias,
+ contract_id=contract_id,
+ contract_type="socket",
+ role=pdef.role,
+ file_path=rel_path,
+ symbol_name=f"{pdef.label}('{identity}')",
+ confidence=pdef.confidence,
+ service=None,
+ meta={
+ "path": identity,
+ "transport": pdef.transport,
+ },
+ )
+ )
+ return contracts
diff --git a/packages/core/src/repowise/core/workspace/system_graph.py b/packages/core/src/repowise/core/workspace/system_graph.py
index 2ccdf084e..4b339a6ea 100644
--- a/packages/core/src/repowise/core/workspace/system_graph.py
+++ b/packages/core/src/repowise/core/workspace/system_graph.py
@@ -64,13 +64,14 @@ SYSTEM_GRAPH_FILENAME = "system_graph.json"
_CONTRACT_TYPE_TO_EDGE_KIND: dict[str, str] = {
"http": "http",
"grpc": "grpc",
+ "socket": "socket",
"topic": "event",
"data": "db",
}
#: All edge kinds the graph can carry. ``db`` carries the shared-table
#: (``data``) contracts; the taxonomy is fixed so views render consistently.
-EDGE_KINDS: tuple[str, ...] = ("http", "grpc", "event", "package", "co_change", "db")
+EDGE_KINDS: tuple[str, ...] = ("http", "grpc", "socket", "event", "package", "co_change", "db")
#: ``match_type`` precedence when several links collapse onto one edge — the most
#: authoritative wins for display. Higher is stronger.
@@ -89,7 +90,7 @@ MAX_EDGE_REFS = 50
#: Structural edges assert a real dependency; behavioral (co-change) edges only
#: assert correlated change. Kept distinct so reachability and the map never
#: conflate "call each other" with "change together".
-_STRUCTURAL_KINDS: frozenset[str] = frozenset({"http", "grpc", "event", "package", "db"})
+_STRUCTURAL_KINDS: frozenset[str] = frozenset({"http", "grpc", "socket", "event", "package", "db"})
def edge_kind_for_contract_type(contract_type: str) -> str:
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index 0fb1a1991..d44e00899 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -245,7 +245,7 @@ async def get_workspace(
async def get_contracts(
ws_config=Depends(get_workspace_config),
enricher=Depends(get_cross_repo_enricher),
- contract_type: str | None = Query(None, description="Filter: http, grpc, topic, or data"),
+ contract_type: str | None = Query(None, description="Filter: http, grpc, socket, topic, or data"),
repo: str | None = Query(None, description="Filter by repo alias"),
role: str | None = Query(None, description="Filter: provider or consumer"),
limit: int = Query(200, ge=1, le=1000),
diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.ts
index d71c0c6cb..a890d4637 100644
--- a/packages/types/src/workspace.ts
+++ b/packages/types/src/workspace.ts
@@ -67,8 +67,15 @@ export interface WorkspacePackageDepEntry {
// uniform: `source` depends on / calls `target`.
// ---------------------------------------------------------------------------
-/** Transport of a system-graph edge. `db` is reserved for a future transport. */
-export type SystemEdgeKind = "http" | "grpc" | "event" | "package" | "co_change" | "db";
+/** Transport of a system-graph edge. */
+export type SystemEdgeKind =
+ | "http"
+ | "grpc"
+ | "socket"
+ | "event"
+ | "package"
+ | "co_change"
+ | "db";
/** How confidently an edge was matched. Behavioral co-change edges are `inferred`. */
export type SystemEdgeMatchType = "exact" | "candidate" | "manual" | "inferred";
diff --git a/packages/ui/__tests__/workspace/contract-links-table.test.tsx b/packages/ui/__tests__/workspace/contract-links-table.test.tsx
index 28a1f1516..992d97c86 100644
--- a/packages/ui/__tests__/workspace/contract-links-table.test.tsx
+++ b/packages/ui/__tests__/workspace/contract-links-table.test.tsx
@@ -44,6 +44,11 @@ describe("ContractLinksTable (virtualized)", () => {
expect(screen.getByText("75%")).toBeInTheDocument();
});
+ it("renders the socket contract type badge", () => {
+ render(<ContractLinksTable links={[link({ contract_type: "socket" })]} />);
+ expect(screen.getByText("Socket")).toBeInTheDocument();
+ });
+
it("shows the provider and consumer file paths", () => {
render(<ContractLinksTable links={[link()]} />);
expect(screen.getByText("src/routes/users.ts")).toBeInTheDocument();
diff --git a/packages/ui/__tests__/workspace/system-map-logic.test.ts b/packages/ui/__tests__/workspace/system-map-logic.test.ts
index 6a821c67e..e226135f4 100644
--- a/packages/ui/__tests__/workspace/system-map-logic.test.ts
+++ b/packages/ui/__tests__/workspace/system-map-logic.test.ts
@@ -162,7 +162,7 @@ describe("applyView", () => {
describe("edge-kind registry", () => {
it("covers every kind in the union and display order", () => {
- expect(EDGE_KIND_ORDER).toHaveLength(6);
+ expect(EDGE_KIND_ORDER).toHaveLength(7);
for (const kind of EDGE_KIND_ORDER) {
const s = edgeKindStyle(kind);
expect(s.label).toBeTruthy();
diff --git a/packages/ui/src/workspace/contract-type-badge.tsx b/packages/ui/src/workspace/contract-type-badge.tsx
index aaff9fd31..4841b01fd 100644
--- a/packages/ui/src/workspace/contract-type-badge.tsx
+++ b/packages/ui/src/workspace/contract-type-badge.tsx
@@ -5,6 +5,7 @@ import { cn } from "../lib/cn";
const TYPE_STYLES: Record<string, { bg: string; text: string; label: string }> = {
http: { bg: "bg-blue-500/10", text: "text-blue-400", label: "HTTP" },
grpc: { bg: "bg-purple-500/10", text: "text-purple-400", label: "gRPC" },
+ socket: { bg: "bg-cyan-500/10", text: "text-cyan-400", label: "Socket" },
topic: { bg: "bg-orange-500/10", text: "text-orange-400", label: "Topic" },
data: { bg: "bg-teal-500/10", text: "text-teal-400", label: "Table" },
};
diff --git a/packages/ui/src/workspace/system-map/edge-kinds.ts b/packages/ui/src/workspace/system-map/edge-kinds.ts
index 3892e37ed..418aa4277 100644
--- a/packages/ui/src/workspace/system-map/edge-kinds.ts
+++ b/packages/ui/src/workspace/system-map/edge-kinds.ts
@@ -12,7 +12,7 @@
* inferred dotted) — see `matchTypeDash`.
*/
-import { ArrowRight, Boxes, Database, Link2, Radio, Zap, type LucideIcon } from "lucide-react";
+import { ArrowRight, Boxes, Database, Link2, Radio, Signal, Zap, type LucideIcon } from "lucide-react";
import type { SystemEdgeKind, SystemEdgeMatchType } from "@repowise-dev/types";
/** Whether an edge reflects a structural contract/dependency or behavioral co-change. */
@@ -36,6 +36,7 @@ export interface SystemEdgeKindStyle {
export const SYSTEM_EDGE_KINDS: Record<SystemEdgeKind, SystemEdgeKindStyle> = {
http: { kind: "http", label: "HTTP", color: "var(--color-accent-secondary)", icon: ArrowRight, category: "structural" },
grpc: { kind: "grpc", label: "gRPC", color: "var(--color-accent-fill)", icon: Zap, category: "structural" },
+ socket: { kind: "socket", label: "Socket", color: "var(--color-info)", icon: Signal, category: "structural" },
event: { kind: "event", label: "Event", color: "var(--color-warning)", icon: Radio, category: "structural" },
package: { kind: "package", label: "Package", color: "var(--color-accent-primary)", icon: Boxes, category: "structural" },
db: { kind: "db", label: "Database", color: "var(--color-text-tertiary)", icon: Database, category: "structural" },
@@ -56,7 +57,7 @@ export function edgeKindStyle(kind: string): SystemEdgeKindStyle {
}
/** Every edge kind, in legend/display order (structural first, behavioral last). */
-export const EDGE_KIND_ORDER: SystemEdgeKind[] = ["http", "grpc", "event", "package", "db", "co_change"];
+export const EDGE_KIND_ORDER: SystemEdgeKind[] = ["http", "grpc", "socket", "event", "package", "db", "co_change"];
/**
* Stroke dash by match confidence: exact / manual links are solid (we trust
diff --git a/packages/web/src/app/workspace/contracts/page.tsx b/packages/web/src/app/workspace/contracts/page.tsx
index b71d1fb3b..c85d48bec 100644
--- a/packages/web/src/app/workspace/contracts/page.tsx
+++ b/packages/web/src/app/workspace/contracts/page.tsx
@@ -20,6 +20,7 @@ const TYPE_OPTIONS = [
{ value: "", label: "All Types" },
{ value: "http", label: "HTTP" },
{ value: "grpc", label: "gRPC" },
+ { value: "socket", label: "Socket" },
{ value: "topic", label: "Topic" },
{ value: "data", label: "Table" },
];
@@ -117,7 +118,7 @@ export default function ContractsPage() {
</h1>
</div>
<p className="text-sm text-[var(--color-text-secondary)]">
- HTTP routes, gRPC services, and message topics detected across repositories.
+ HTTP routes, gRPC services, socket endpoints, and message topics detected across repositories.
</p>
</div>
diff --git a/tests/unit/workspace/test_contract_config.py b/tests/unit/workspace/test_contract_config.py
index 3c2716b33..8bef1bbbd 100644
--- a/tests/unit/workspace/test_contract_config.py
+++ b/tests/unit/workspace/test_contract_config.py
@@ -15,6 +15,7 @@ class TestContractConfig:
cfg = ContractConfig()
assert cfg.detect_http is True
assert cfg.detect_grpc is True
+ assert cfg.detect_socket is True
assert cfg.detect_topics is True
assert cfg.manual_links == []
@@ -22,12 +23,14 @@ class TestContractConfig:
cfg = ContractConfig.from_dict({"detect_http": False})
assert cfg.detect_http is False
assert cfg.detect_grpc is True
+ assert cfg.detect_socket is True
assert cfg.detect_topics is True
def test_round_trip(self) -> None:
cfg = ContractConfig(
detect_http=True,
detect_grpc=False,
+ detect_socket=True,
detect_topics=True,
manual_links=[
ManualContractLink(
@@ -99,11 +102,13 @@ class TestWorkspaceConfigWithContracts:
"contracts": {
"detect_http": True,
"detect_grpc": False,
+ "detect_socket": False,
"detect_topics": True,
},
}
cfg = WorkspaceConfig.from_dict(data)
assert cfg.contracts.detect_grpc is False
+ assert cfg.contracts.detect_socket is False
def test_round_trip_with_manual_links(self, tmp_path) -> None:
cfg = WorkspaceConfig(
@@ -113,6 +118,7 @@ class TestWorkspaceConfigWithContracts:
contracts=ContractConfig(
detect_http=True,
detect_grpc=True,
+ detect_socket=False,
detect_topics=False,
manual_links=[
ManualContractLink(
@@ -126,6 +132,7 @@ class TestWorkspaceConfigWithContracts:
)
cfg.save(tmp_path)
loaded = WorkspaceConfig.load(tmp_path)
+ assert loaded.contracts.detect_socket is False
assert loaded.contracts.detect_topics is False
assert len(loaded.contracts.manual_links) == 1
assert loaded.contracts.manual_links[0].contract_id == "http::GET::/jobs"
diff --git a/tests/unit/workspace/test_contracts.py b/tests/unit/workspace/test_contracts.py
index d592c3c60..836485615 100644
--- a/tests/unit/workspace/test_contracts.py
+++ b/tests/unit/workspace/test_contracts.py
@@ -2,11 +2,8 @@
from __future__ import annotations
-import json
from pathlib import Path
-import pytest
-
from repowise.core.workspace.contracts import (
CONTRACTS_FILENAME,
Contract,
@@ -18,21 +15,18 @@ from repowise.core.workspace.contracts import (
normalize_contract_id,
save_contract_store,
)
+from repowise.core.workspace.extractors.grpc_extractor import GrpcExtractor
from repowise.core.workspace.extractors.http_extractor import (
HttpExtractor,
normalize_http_path,
)
-from repowise.core.workspace.extractors.grpc_extractor import (
- GrpcExtractor,
- _extract_service_blocks,
-)
-from repowise.core.workspace.extractors.topic_extractor import TopicExtractor
from repowise.core.workspace.extractors.service_boundary import (
ServiceBoundary,
assign_service,
detect_service_boundaries,
)
-
+from repowise.core.workspace.extractors.socket_extractor import SocketExtractor
+from repowise.core.workspace.extractors.topic_extractor import TopicExtractor
# ---------------------------------------------------------------------------
# normalize_http_path
@@ -841,9 +835,123 @@ class TestNormalizeContractId:
result = normalize_contract_id("grpc::PKG.Service/GetUser")
assert result == "grpc::pkg.service/GetUser"
+ def test_socket_normalizes(self) -> None:
+ assert normalize_contract_id("socket::/Game/State/") == "socket::/game/state"
+
def test_topic_lowercases(self) -> None:
assert normalize_contract_id("topic::Orders") == "topic::orders"
+class TestSocketExtractor:
+ def _write_file(self, repo: Path, rel: str, content: str) -> None:
+ fpath = repo / rel
+ fpath.parent.mkdir(parents=True, exist_ok=True)
+ fpath.write_text(content, encoding="utf-8")
+
+ def test_csharp_clientwebsocket_consumer(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "Net.cs", """
+ using System.Net.WebSockets;
+ var socket = new ClientWebSocket();
+ await socket.ConnectAsync(new Uri("wss://backend.example.com/game/state"), token);
+ """)
+ consumers = [c for c in SocketExtractor().extract(tmp_path, "unity") if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "socket::/game/state"
+ assert consumers[0].meta["transport"] == "clientwebsocket"
+
+ def test_signalr_consumer_strips_base_expr(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "HubClient.cs", """
+ using Microsoft.AspNetCore.SignalR.Client;
+ var connection = new HubConnectionBuilder()
+ .WithUrl($"{baseUrl}/hubs/game")
+ .Build();
+ """)
+ consumers = [c for c in SocketExtractor().extract(tmp_path, "unity") if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "socket::/hubs/game"
+ assert consumers[0].meta["transport"] == "signalr"
+
+ def test_native_websocket_consumer_requires_context(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "SocketClient.cs", """
+ using NativeWebSocket;
+ var ws = new WebSocket($"{baseUrl}/ws/lobby");
+ """)
+ consumers = [c for c in SocketExtractor().extract(tmp_path, "unity") if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "socket::/ws/lobby"
+ assert consumers[0].meta["transport"] == "nativewebsocket"
+
+ def test_websocketsharp_fully_qualified_constructor(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "SocketClient.cs", """
+ using WebSocketSharp;
+ var ws = new WebSocketSharp.WebSocket("wss://backend.example.com/ws/lobby");
+ """)
+ consumers = [c for c in SocketExtractor().extract(tmp_path, "unity") if c.role == "consumer"]
+ assert len(consumers) == 1
+ assert consumers[0].contract_id == "socket::/ws/lobby"
+ assert consumers[0].meta["transport"] == "websocketsharp"
+
+ def test_signalr_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "Program.cs", """
+ app.MapHub<GameHub>("/hubs/game");
+ """)
+ providers = [c for c in SocketExtractor().extract(tmp_path, "backend") if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "socket::/hubs/game"
+ assert providers[0].meta["transport"] == "signalr"
+
+ def test_fastapi_websocket_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "main.py", """
+ @app.websocket("/ws/chat/{room_id}")
+ async def room_socket(): ...
+ """)
+ providers = [c for c in SocketExtractor().extract(tmp_path, "backend") if c.role == "provider"]
+ assert len(providers) == 1
+ assert providers[0].contract_id == "socket::/ws/chat/{param}"
+
+ def test_fastapi_unknown_websocket_decorator_not_a_provider(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "main.py", """
+ @metrics.websocket("/ws/chat/{room_id}")
+ async def room_socket(): ...
+ """)
+ providers = [c for c in SocketExtractor().extract(tmp_path, "backend") if c.role == "provider"]
+ assert providers == []
+
+ def test_signalr_provider_file_does_not_emit_consumer_from_unrelated_withurl(self, tmp_path: Path) -> None:
+ self._write_file(tmp_path, "Program.cs", """
+ app.MapHub<GameHub>("/hubs/game");
+ client.WithUrl("/not-a-socket-provider");
+ """)
+ consumers = [c for c in SocketExtractor().extract(tmp_path, "backend") if c.role == "consumer"]
+ providers = [c for c in SocketExtractor().extract(tmp_path, "backend") if c.role == "provider"]
+ assert consumers == []
+ assert len(providers) == 1
+ assert providers[0].contract_id == "socket::/hubs/game"
+
+ def test_same_path_matches_exactly(self) -> None:
+ contracts = [
+ Contract(
+ repo="backend",
+ contract_id="socket::/hubs/game",
+ contract_type="socket",
+ role="provider",
+ file_path="Program.cs",
+ symbol_name="MapHub",
+ confidence=0.85,
+ ),
+ Contract(
+ repo="unity",
+ contract_id="socket::/hubs/game",
+ contract_type="socket",
+ role="consumer",
+ file_path="HubClient.cs",
+ symbol_name="WithUrl",
+ confidence=0.8,
+ ),
+ ]
+ links = match_contracts(contracts)
+ assert len(links) == 1
+ assert links[0].contract_type == "socket"
+
# ---------------------------------------------------------------------------
# match_contracts
diff --git a/tests/unit/workspace/test_system_graph.py b/tests/unit/workspace/test_system_graph.py
index 9a82bfc38..9675e2a3e 100644
--- a/tests/unit/workspace/test_system_graph.py
+++ b/tests/unit/workspace/test_system_graph.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from pathlib import Path
-from repowise.core.workspace.contracts import Contract, ContractLink, ContractStore
+from repowise.core.workspace.contracts import Contract, ContractLink
from repowise.core.workspace.cross_repo import (
CrossRepoCoChange,
CrossRepoOverlay,
@@ -121,6 +121,7 @@ def test_monorepo_yields_multiple_service_nodes():
def test_contract_type_to_edge_kind():
assert edge_kind_for_contract_type("http") == "http"
assert edge_kind_for_contract_type("grpc") == "grpc"
+ assert edge_kind_for_contract_type("socket") == "socket"
assert edge_kind_for_contract_type("topic") == "event"
assert edge_kind_for_contract_type("unknown") == "unknown"
@@ -152,6 +153,16 @@ def test_topic_contract_becomes_event_edge():
assert graph.edges[0].kind == "event"
+def test_socket_contract_becomes_socket_edge():
+ contracts = [
+ _provider("api", "socket::/hubs/game", ctype="socket", file="api/hub.cs"),
+ _consumer("unity", "socket::/hubs/game", ctype="socket", file="unity/net.cs"),
+ ]
+ links = [_link("socket::/hubs/game", "api", "api/hub.cs", "unity", "unity/net.cs", ctype="socket")]
+ graph = build_system_graph(contracts, links, CrossRepoOverlay(), {})
+ assert graph.edges[0].kind == "socket"
+
+
def test_parallel_links_aggregate_into_one_weighted_edge():
contracts = [
_provider("api", "http::GET::/a", file="api/h.py"),