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): expose contract line, symbol and schema over REST (#1898)

Raghav Chamadiya31eb9da35ca8
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.md
index 197a8a1d2..e7dec5563 100644
--- a/docs/scale/WORKSPACES.md
+++ b/docs/scale/WORKSPACES.md
@@ -238,6 +238,17 @@ whose base URL is an unresolved placeholder (`fetch(\`${API_BASE}/users\`)`) mat
on the host-relative path; the link is **exact** when exactly one workspace service
provides that path and a lower-confidence **candidate** when the target is ambiguous.
+**Over REST.** `GET /api/workspace/contracts` lists contracts and links,
+filterable by `contract_type`, `repo` and `role`. Each contract carries its
+line, its ingestion symbol id and the extractor's `meta`; each link carries both
+symbol ids and both service boundaries. The request/response `schema` is not on
+the list, because it runs to full inline type declarations and only one is ever
+needed at a time: fetch it with
+`GET /api/workspace/contracts/detail?repo=<alias>&file=<path>&id=<contract-id>`,
+which returns that one contract with its schema, its links, and its unmatched
+reason. All three parameters are required, since a contract id alone is not
+unique across repos.
+
**Tuning extraction** via the `contracts:` block in `.repowise-workspace.yaml`:
```yaml
diff --git a/packages/api-client/src/types/workspace.ts b/packages/api-client/src/types/workspace.ts
index d290ed340..865f59baa 100644
--- a/packages/api-client/src/types/workspace.ts
+++ b/packages/api-client/src/types/workspace.ts
@@ -68,6 +68,22 @@ export interface WorkspaceContractEntry {
symbol_name: string;
confidence: number;
service: string | null;
+ /**
+ * 1-indexed line of the declaration or call. Null when the contract never
+ * bound to a line.
+ */
+ line: number | null;
+ /**
+ * Ingestion symbol id (`"<rel_path>::<name>"`). Null when the repo has no
+ * index or nothing is declared at `line` — the contract still matches, it
+ * just cannot be traversed into the call graph.
+ */
+ symbol_id: string | null;
+ /**
+ * Extractor-supplied detail (`extraction_layer`, `framework`, `method`,
+ * `path`, `table`, `package`...). Keys vary by contract type.
+ */
+ meta: Record<string, unknown>;
}
export interface WorkspaceContractLinkEntry {
@@ -81,6 +97,20 @@ export interface WorkspaceContractLinkEntry {
consumer_repo: string;
consumer_file: string;
consumer_symbol: string;
+ /**
+ * Service boundary the provider sits behind, when the workspace declares one.
+ * Matching skips a pair only when the repo *and* the service are the same, so
+ * this is what explains a link between two services inside one repo.
+ */
+ provider_service: string | null;
+ /** The same, for the calling side. */
+ consumer_service: string | null;
+ /**
+ * The linked contracts' symbol ids, so a caller can name the code rather than
+ * a display label. Null when that side never bound to one.
+ */
+ provider_symbol_id: string | null;
+ consumer_symbol_id: string | null;
}
export interface WorkspaceContractsResponse {
@@ -91,6 +121,31 @@ export interface WorkspaceContractsResponse {
by_type: Record<string, number>;
}
+/**
+ * One contract, keyed by `(repo, file_path, contract_id)`.
+ *
+ * Carries the request/response shape the list endpoint deliberately withholds:
+ * `schema` is present on roughly a third of contracts and single rows run to
+ * full inline type declarations, so it is affordable one at a time and not 200
+ * at a time.
+ */
+export interface WorkspaceContractDetail {
+ contract: WorkspaceContractEntry;
+ /**
+ * The artifact's `schema` block, named around Pydantic — a field literally
+ * called `schema` shadows an attribute of `BaseModel`.
+ */
+ contract_schema: Record<string, unknown> | null;
+ /** Links this contract participates in, on whichever side it plays. */
+ links: WorkspaceContractLinkEntry[];
+ /**
+ * Why this consumer matched no provider (`external_host`, `internal_only`,
+ * `no_provider`). Null for providers, for linked consumers, and when no
+ * system graph is built.
+ */
+ unmatched_reason: string | null;
+}
+
export interface WorkspaceCoChangeEntry {
source_repo: string;
source_file: string;
diff --git a/packages/api-client/src/workspace.ts b/packages/api-client/src/workspace.ts
index 8454dd2b2..d936a05dd 100644
--- a/packages/api-client/src/workspace.ts
+++ b/packages/api-client/src/workspace.ts
@@ -2,6 +2,7 @@ import { apiGet, apiPost } from "./client";
import type {
WorkspaceResponse,
WorkspaceContractsResponse,
+ WorkspaceContractDetail,
WorkspaceCoChangesResponse,
WorkspaceGraphResponse,
WorkspaceSyncResponse,
@@ -35,6 +36,24 @@ export async function getWorkspaceContracts(opts?: {
return apiGet<WorkspaceContractsResponse>("/api/workspace/contracts", params);
}
+/**
+ * One contract with its schema, its links, and its unmatched reason.
+ *
+ * Keyed by all three of `repo`, `file` and `id` because `id` alone is not
+ * unique — several repos declare the same `http::GET::/user`. Query params
+ * rather than a path segment because `file` carries slashes.
+ */
+export async function getWorkspaceContractDetail(
+ opts: { repo: string; file: string; id: string },
+ fetchOptions?: RequestInit,
+): Promise<WorkspaceContractDetail> {
+ return apiGet<WorkspaceContractDetail>(
+ "/api/workspace/contracts/detail",
+ { repo: opts.repo, file: opts.file, id: opts.id },
+ fetchOptions,
+ );
+}
+
export async function getWorkspaceCoChanges(opts?: {
repo?: string;
min_strength?: number;
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index 8cc5cd1da..bceee8f3a 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -27,6 +27,7 @@ from repowise.server.schemas import (
WorkspaceCoChangeEntry,
WorkspaceCoChangesResponse,
WorkspaceConformanceResponse,
+ WorkspaceContractDetail,
WorkspaceContractEntry,
WorkspaceContractLinkEntry,
WorkspaceContractsResponse,
@@ -245,6 +246,47 @@ async def get_workspace(
)
+def _contract_entry(c: dict) -> WorkspaceContractEntry:
+ """Project one raw ``contracts.json`` row onto the wire model.
+
+ ``schema`` is dropped on purpose — it is the one field the list endpoint
+ cannot afford and the detail endpoint carries separately.
+ """
+ return WorkspaceContractEntry(
+ contract_id=c.get("contract_id", ""),
+ contract_type=c.get("contract_type", ""),
+ role=c.get("role", ""),
+ repo=c.get("repo", ""),
+ file_path=c.get("file_path", ""),
+ symbol_name=c.get("symbol_name", ""),
+ confidence=c.get("confidence", 0.0),
+ service=c.get("service"),
+ line=c.get("line"),
+ symbol_id=c.get("symbol_id"),
+ meta=c.get("meta") or {},
+ )
+
+
+def _contract_link(lk: dict) -> WorkspaceContractLinkEntry:
+ """Project one raw ``contract_links`` row onto the wire model."""
+ return WorkspaceContractLinkEntry(
+ contract_id=lk.get("contract_id", ""),
+ contract_type=lk.get("contract_type", ""),
+ match_type=lk.get("match_type", "exact"),
+ confidence=lk.get("confidence", 0.0),
+ provider_repo=lk.get("provider_repo", ""),
+ provider_file=lk.get("provider_file", ""),
+ provider_symbol=lk.get("provider_symbol", ""),
+ consumer_repo=lk.get("consumer_repo", ""),
+ consumer_file=lk.get("consumer_file", ""),
+ consumer_symbol=lk.get("consumer_symbol", ""),
+ provider_service=lk.get("provider_service"),
+ consumer_service=lk.get("consumer_service"),
+ provider_symbol_id=lk.get("provider_symbol_id"),
+ consumer_symbol_id=lk.get("consumer_symbol_id"),
+ )
+
+
# ---------------------------------------------------------------------------
# GET /api/workspace/contracts
# ---------------------------------------------------------------------------
@@ -299,40 +341,99 @@ async def get_contracts(
contracts_page = contracts[offset : offset + limit]
return WorkspaceContractsResponse(
- contracts=[
- WorkspaceContractEntry(
- contract_id=c.get("contract_id", ""),
- contract_type=c.get("contract_type", ""),
- role=c.get("role", ""),
- repo=c.get("repo", ""),
- file_path=c.get("file_path", ""),
- symbol_name=c.get("symbol_name", ""),
- confidence=c.get("confidence", 0.0),
- service=c.get("service"),
- )
- for c in contracts_page
- ],
- links=[
- WorkspaceContractLinkEntry(
- contract_id=lk.get("contract_id", ""),
- contract_type=lk.get("contract_type", ""),
- match_type=lk.get("match_type", "exact"),
- confidence=lk.get("confidence", 0.0),
- provider_repo=lk.get("provider_repo", ""),
- provider_file=lk.get("provider_file", ""),
- provider_symbol=lk.get("provider_symbol", ""),
- consumer_repo=lk.get("consumer_repo", ""),
- consumer_file=lk.get("consumer_file", ""),
- consumer_symbol=lk.get("consumer_symbol", ""),
- )
- for lk in links
- ],
+ contracts=[_contract_entry(c) for c in contracts_page],
+ links=[_contract_link(lk) for lk in links],
total_contracts=total_contracts,
total_links=total_links,
by_type=by_type,
)
+# ---------------------------------------------------------------------------
+# GET /api/workspace/contracts/detail
+# ---------------------------------------------------------------------------
+
+
+def _unmatched_reason(enricher, repo: str, file_path: str, contract_id: str) -> str | None:
+ """Look up why one consumer matched nothing, from the system graph.
+
+ The reasons live in ``system_graph.json``, not ``contracts.json``, and are
+ keyed by the same ``(repo, file_path, contract_id)`` triple this endpoint
+ takes. Returns None when no graph is built or the consumer did match.
+ """
+ diagnostics = enricher.get_diagnostics() or {}
+ for u in diagnostics.get("unmatched_consumers", []):
+ if (
+ u.get("repo") == repo
+ and u.get("file_path") == file_path
+ and u.get("contract_id") == contract_id
+ ):
+ return u.get("reason")
+ return None
+
+
[email protected]("/contracts/detail", response_model=WorkspaceContractDetail)
+async def get_contract_detail(
+ ws_config=Depends(get_workspace_config),
+ enricher=Depends(get_cross_repo_enricher),
+ repo: str = Query(..., description="Repo alias the contract was extracted from"),
+ file: str = Query(..., description="File path, relative to that repo's root"),
+ id: str = Query(..., description="Contract id, e.g. 'http::GET::/api/users'"),
+):
+ """One contract with its schema, its links, and its unmatched reason.
+
+ Keyed by query parameters rather than a path segment because ``file`` is a
+ path and carries slashes. All three are required: ``id`` alone is not
+ unique, several repos declare the same ``http::GET::/user``.
+
+ The triple is the shareable identity, not a primary key. One file may call
+ the same endpoint from two lines; when it does, the first row wins. The link
+ list is filtered by the same triple, so it is identical whichever row wins;
+ the enclosing symbol is not, so the response names one of the call sites.
+ Keying on the line instead would rot every saved link on an edit above the
+ call.
+ """
+ _require_workspace(ws_config)
+
+ if enricher is None:
+ raise HTTPException(status_code=404, detail="No contract data for this workspace")
+
+ match = next(
+ (
+ c
+ for c in getattr(enricher, "_contracts", [])
+ if c.get("repo") == repo
+ and c.get("file_path") == file
+ and c.get("contract_id") == id
+ ),
+ None,
+ )
+ if match is None:
+ raise HTTPException(status_code=404, detail="Contract not found")
+
+ role = match.get("role", "")
+ if role == "consumer":
+ repo_key, file_key = "consumer_repo", "consumer_file"
+ else:
+ repo_key, file_key = "provider_repo", "provider_file"
+ links = [
+ lk
+ for lk in getattr(enricher, "_contract_links", [])
+ if lk.get("contract_id") == id and lk.get(repo_key) == repo and lk.get(file_key) == file
+ ]
+
+ reason = None
+ if role == "consumer" and not links:
+ reason = _unmatched_reason(enricher, repo, file, id)
+
+ return WorkspaceContractDetail(
+ contract=_contract_entry(match),
+ contract_schema=match.get("schema"),
+ links=[_contract_link(lk) for lk in links],
+ unmatched_reason=reason,
+ )
+
+
# ---------------------------------------------------------------------------
# GET /api/workspace/co-changes
# ---------------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 2d714e80b..44acc144a 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -192,6 +192,7 @@ from .workspace import (
WorkspaceCoChangesResponse,
WorkspaceConformanceResponse,
WorkspaceConformanceViolation,
+ WorkspaceContractDetail,
WorkspaceContractEntry,
WorkspaceContractLinkEntry,
WorkspaceContractsResponse,
@@ -367,6 +368,7 @@ __all__ = [
"WorkspaceCoChangesResponse",
"WorkspaceConformanceResponse",
"WorkspaceConformanceViolation",
+ "WorkspaceContractDetail",
"WorkspaceContractEntry",
"WorkspaceContractLinkEntry",
"WorkspaceContractSummary",
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index 83848b81f..f93ca3db6 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -84,6 +84,16 @@ class WorkspaceContractEntry(BaseModel):
symbol_name: str
confidence: float
service: str | None = None
+ #: 1-indexed line of the declaration or call. None when the contract never
+ #: bound to a line.
+ line: int | None = None
+ #: Ingestion symbol id (``"<rel_path>::<name>"``). None when the repo has no
+ #: index or nothing is declared at ``line`` — the contract still matches, it
+ #: just cannot be traversed into the call graph.
+ symbol_id: str | None = None
+ #: Extractor-supplied detail (``extraction_layer``, ``framework``, ``method``,
+ #: ``path``, ``table``, ``package``...). Keys vary by contract type.
+ meta: dict = {}
class WorkspaceContractLinkEntry(BaseModel):
@@ -97,6 +107,17 @@ class WorkspaceContractLinkEntry(BaseModel):
consumer_repo: str
consumer_file: str
consumer_symbol: str
+ #: Service boundary the provider sits behind, when the workspace declares
+ #: one. Matching skips a pair only when the repo *and* the service are the
+ #: same, so this is what explains a link between two services inside one
+ #: repo.
+ provider_service: str | None = None
+ #: The same, for the calling side.
+ consumer_service: str | None = None
+ #: The linked contracts' symbol ids, so a caller can name the code rather
+ #: than a display label. None when that side never bound to one.
+ provider_symbol_id: str | None = None
+ consumer_symbol_id: str | None = None
class WorkspaceContractsResponse(BaseModel):
@@ -107,6 +128,27 @@ class WorkspaceContractsResponse(BaseModel):
by_type: dict[str, int] = {}
+class WorkspaceContractDetail(BaseModel):
+ """One contract, keyed by ``(repo, file_path, contract_id)``.
+
+ Carries the request/response shape that the list endpoint deliberately
+ withholds: ``schema`` is present on roughly a third of contracts and single
+ rows run to full inline type declarations, so it is affordable one at a time
+ and not 200 at a time.
+ """
+
+ contract: WorkspaceContractEntry
+ #: The artifact's ``schema`` block, named around Pydantic — a field literally
+ #: called ``schema`` shadows an attribute of ``BaseModel``.
+ contract_schema: dict | None = None
+ #: Links this contract participates in, on whichever side it plays.
+ links: list[WorkspaceContractLinkEntry] = []
+ #: Why this consumer matched no provider (``external_host``,
+ #: ``internal_only``, ``no_provider``), from the system graph's diagnostics.
+ #: None for providers, for linked consumers, and when no graph is built.
+ unmatched_reason: str | None = None
+
+
class WorkspaceCoChangeEntry(BaseModel):
source_repo: str
source_file: str
diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.ts
index 033888c4e..46774c1c9 100644
--- a/packages/types/src/workspace.ts
+++ b/packages/types/src/workspace.ts
@@ -40,6 +40,20 @@ export interface WorkspaceContractLinkEntry {
consumer_repo: string;
consumer_file: string;
consumer_symbol: string;
+ /**
+ * Service boundary the provider sits behind, when the workspace declares one.
+ * Matching skips a pair only when the repo *and* the service are the same, so
+ * this is what explains a link between two services inside one repo.
+ */
+ provider_service: string | null;
+ /** The same, for the calling side. */
+ consumer_service: string | null;
+ /**
+ * The linked contracts' symbol ids, so a caller can name the code rather than
+ * a display label. Null when that side never bound to one.
+ */
+ provider_symbol_id: string | null;
+ consumer_symbol_id: string | null;
}
export interface WorkspaceCoChangeEntry {
diff --git a/packages/ui/__tests__/workspace/contract-links-table.test.tsx b/packages/ui/__tests__/workspace/contract-links-table.test.tsx
index 992d97c86..e52f5f3e3 100644
--- a/packages/ui/__tests__/workspace/contract-links-table.test.tsx
+++ b/packages/ui/__tests__/workspace/contract-links-table.test.tsx
@@ -17,6 +17,10 @@ function link(
consumer_repo: "web-app",
consumer_file: "src/api/users-client.ts",
consumer_symbol: "fetchUser",
+ provider_service: null,
+ consumer_service: null,
+ provider_symbol_id: null,
+ consumer_symbol_id: null,
...overrides,
};
}
diff --git a/packages/web/src/app/workspace/contracts/contracts-table.tsx b/packages/web/src/app/workspace/contracts/contracts-table.tsx
index 1b79c01e0..da326ba23 100644
--- a/packages/web/src/app/workspace/contracts/contracts-table.tsx
+++ b/packages/web/src/app/workspace/contracts/contracts-table.tsx
@@ -71,7 +71,14 @@ export function ContractsTable({ contracts }: { contracts: WorkspaceContractEntr
return (
<ResponsiveTable
columns={CONTRACT_COLUMNS}
- rows={contracts.map((c, i) => ({ ...c, _key: `${c.contract_id}|${i}` }))}
+ rows={contracts.map((c) => ({
+ // The contract identity, not the array index: an index renumbers every
+ // row whenever a filter changes. `line` is part of the key because one
+ // file can call the same endpoint from two places, which is a duplicate
+ // React key without it.
+ ...c,
+ _key: `${c.repo}|${c.file_path}|${c.contract_id}|${c.line ?? ""}`,
+ }))}
rowKey={(c) => c._key}
caption="All detected contracts"
stacked="md"
diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.py
index f04f0bb5a..927a441d5 100644
--- a/tests/unit/server/test_workspace_router.py
+++ b/tests/unit/server/test_workspace_router.py
@@ -119,6 +119,14 @@ def _make_enricher(tmp_path: Path) -> CrossRepoEnricher:
"symbol_name": "get_users",
"confidence": 0.85,
"service": None,
+ "line": 42,
+ "symbol_id": "routes.py::get_users",
+ "meta": {"extraction_layer": "index", "framework": "fastapi"},
+ "schema": {
+ "source": "signature",
+ "request_fields": [{"name": "limit", "type": "int"}],
+ "response_fields": [{"name": "id", "type": "int", "required": True}],
+ },
},
{
"repo": "frontend",
@@ -129,6 +137,9 @@ def _make_enricher(tmp_path: Path) -> CrossRepoEnricher:
"symbol_name": "fetchUsers",
"confidence": 0.75,
"service": None,
+ "line": 7,
+ "symbol_id": "client.ts::fetchUsers",
+ "meta": {"extraction_layer": "index", "client": "fetch"},
},
{
"repo": "backend",
@@ -140,6 +151,19 @@ def _make_enricher(tmp_path: Path) -> CrossRepoEnricher:
"confidence": 0.85,
"service": None,
},
+ {
+ # A consumer nothing provides — the row the detail endpoint
+ # reports an unmatched reason for.
+ "repo": "backend",
+ "contract_id": "http::POST::/api/embed",
+ "contract_type": "http",
+ "role": "consumer",
+ "file_path": "ollama.py",
+ "symbol_name": "embed",
+ "confidence": 0.7,
+ "service": None,
+ "line": 88,
+ },
],
"contract_links": [
{
@@ -153,12 +177,44 @@ def _make_enricher(tmp_path: Path) -> CrossRepoEnricher:
"consumer_repo": "frontend",
"consumer_file": "client.ts",
"consumer_symbol": "fetchUsers",
+ "provider_service": "services/api",
+ "consumer_service": "services/web",
+ "provider_symbol_id": "routes.py::get_users",
+ "consumer_symbol_id": "client.ts::fetchUsers",
},
],
},
)
- return CrossRepoEnricher(cross_repo_path, contracts_path=contracts_path)
+ # Unmatched reasons live in the system graph, not in contracts.json.
+ system_graph_path = tmp_path / "system_graph.json"
+ _write_json(
+ system_graph_path,
+ {
+ "version": 1,
+ "generated_at": "2026-04-12T12:00:00Z",
+ "nodes": [],
+ "edges": [],
+ "diagnostics": {
+ "unmatched_consumers": [
+ {
+ "repo": "backend",
+ "file_path": "ollama.py",
+ "contract_id": "http::POST::/api/embed",
+ "contract_type": "http",
+ "reason": "no_provider",
+ },
+ ],
+ "unmatched_by_reason": {"no_provider": 1},
+ },
+ },
+ )
+
+ return CrossRepoEnricher(
+ cross_repo_path,
+ contracts_path=contracts_path,
+ system_graph_path=system_graph_path,
+ )
def _create_workspace_repo_db(
@@ -277,9 +333,9 @@ class TestGetWorkspace:
async with AsyncClient(transport=transport, base_url="http://test") as c:
resp = await c.get("/api/workspace")
data = resp.json()
- assert data["contract_summary"]["total_contracts"] == 3
+ assert data["contract_summary"]["total_contracts"] == 4
assert data["contract_summary"]["total_links"] == 1
- assert data["contract_summary"]["by_type"]["http"] == 2
+ assert data["contract_summary"]["by_type"]["http"] == 3
@pytest.mark.asyncio
async def test_no_enricher(self) -> None:
@@ -321,9 +377,9 @@ class TestGetContracts:
resp = await c.get("/api/workspace/contracts")
assert resp.status_code == 200
data = resp.json()
- assert data["total_contracts"] == 3
+ assert data["total_contracts"] == 4
assert data["total_links"] == 1
- assert len(data["contracts"]) == 3
+ assert len(data["contracts"]) == 4
assert len(data["links"]) == 1
@pytest.mark.asyncio
@@ -380,6 +436,185 @@ class TestGetContracts:
assert data["total_links"] == 0
+class TestContractWireFields:
+ """The list endpoint carries everything but ``schema``."""
+
+ @pytest.mark.asyncio
+ async def test_entry_carries_line_symbol_id_and_meta(self, tmp_path: Path) -> None:
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=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/contracts")
+ entry = next(e for e in resp.json()["contracts"] if e["symbol_name"] == "get_users")
+ assert entry["line"] == 42
+ assert entry["symbol_id"] == "routes.py::get_users"
+ assert entry["meta"]["framework"] == "fastapi"
+
+ @pytest.mark.asyncio
+ async def test_entry_tolerates_a_row_without_them(self, tmp_path: Path) -> None:
+ """A contract that never bound to a line still serializes."""
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=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/contracts")
+ entry = next(e for e in resp.json()["contracts"] if e["symbol_name"] == "Login")
+ assert entry["line"] is None
+ assert entry["symbol_id"] is None
+ assert entry["meta"] == {}
+
+ @pytest.mark.asyncio
+ async def test_schema_stays_off_the_list(self, tmp_path: Path) -> None:
+ """``schema`` is the one field the list must not carry - it is the bulk."""
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=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/contracts")
+ for entry in resp.json()["contracts"]:
+ assert "schema" not in entry
+ assert "contract_schema" not in entry
+
+ @pytest.mark.asyncio
+ async def test_link_carries_symbol_ids_and_provider_service(self, tmp_path: Path) -> None:
+ ws_config = _make_ws_config()
+ enricher = _make_enricher(tmp_path)
+ app = _make_workspace_app(ws_config=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/contracts")
+ link = resp.json()["links"][0]
+ assert link["provider_service"] == "services/api"
+ assert link["consumer_service"] == "services/web"
+ assert link["provider_symbol_id"] == "routes.py::get_users"
+ assert link["consumer_symbol_id"] == "client.ts::fetchUsers"
+
+
+# ---------------------------------------------------------------------------
+# Tests — GET /api/workspace/contracts/detail
+# ---------------------------------------------------------------------------
+
+
+class TestGetContractDetail:
+ @staticmethod
+ def _app(tmp_path: Path):
+ return _make_workspace_app(ws_config=_make_ws_config(), enricher=_make_enricher(tmp_path))
+
+ @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/contracts/detail",
+ params={"repo": "backend", "file": "routes.py", "id": "http::GET::/api/users"},
+ )
+ assert resp.status_code == 404
+
+ @pytest.mark.asyncio
+ async def test_provider_returns_schema_and_link(self, tmp_path: Path) -> None:
+ """The whole point of the route: one contract, with its schema."""
+ transport = ASGITransport(app=self._app(tmp_path))
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get(
+ "/api/workspace/contracts/detail",
+ params={"repo": "backend", "file": "routes.py", "id": "http::GET::/api/users"},
+ )
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["contract"]["symbol_name"] == "get_users"
+ assert data["contract_schema"]["source"] == "signature"
+ assert data["contract_schema"]["response_fields"][0]["name"] == "id"
+ assert len(data["links"]) == 1
+ assert data["links"][0]["consumer_repo"] == "frontend"
+ assert data["unmatched_reason"] is None
+
+ @pytest.mark.asyncio
+ async def test_consumer_side_finds_its_link(self, tmp_path: Path) -> None:
+ """A consumer matches on the consumer columns, not the provider ones."""
+ transport = ASGITransport(app=self._app(tmp_path))
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get(
+ "/api/workspace/contracts/detail",
+ params={"repo": "frontend", "file": "client.ts", "id": "http::GET::/api/users"},
+ )
+ data = resp.json()
+ assert data["contract"]["role"] == "consumer"
+ assert len(data["links"]) == 1
+ assert data["contract_schema"] is None
+ assert data["unmatched_reason"] is None
+
+ @pytest.mark.asyncio
+ async def test_unmatched_consumer_reports_its_reason(self, tmp_path: Path) -> None:
+ transport = ASGITransport(app=self._app(tmp_path))
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get(
+ "/api/workspace/contracts/detail",
+ params={"repo": "backend", "file": "ollama.py", "id": "http::POST::/api/embed"},
+ )
+ data = resp.json()
+ assert data["links"] == []
+ assert data["unmatched_reason"] == "no_provider"
+
+ @pytest.mark.asyncio
+ async def test_orphan_provider_has_no_reason(self, tmp_path: Path) -> None:
+ """A provider nobody calls is the normal state, not an unmatched one."""
+ transport = ASGITransport(app=self._app(tmp_path))
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get(
+ "/api/workspace/contracts/detail",
+ params={"repo": "backend", "file": "auth.py", "id": "grpc::Auth/Login"},
+ )
+ data = resp.json()
+ assert data["links"] == []
+ assert data["unmatched_reason"] is None
+
+ @pytest.mark.asyncio
+ async def test_repo_is_part_of_the_identity(self, tmp_path: Path) -> None:
+ """The same contract_id in the wrong repo is a miss, not the other row."""
+ transport = ASGITransport(app=self._app(tmp_path))
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get(
+ "/api/workspace/contracts/detail",
+ params={"repo": "frontend", "file": "routes.py", "id": "http::GET::/api/users"},
+ )
+ assert resp.status_code == 404
+
+ @pytest.mark.asyncio
+ async def test_unknown_contract(self, tmp_path: Path) -> None:
+ transport = ASGITransport(app=self._app(tmp_path))
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get(
+ "/api/workspace/contracts/detail",
+ params={"repo": "backend", "file": "nope.py", "id": "http::GET::/nope"},
+ )
+ assert resp.status_code == 404
+
+ @pytest.mark.asyncio
+ async def test_missing_param_is_rejected(self, tmp_path: Path) -> None:
+ """All three identity params are required."""
+ transport = ASGITransport(app=self._app(tmp_path))
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get("/api/workspace/contracts/detail", params={"repo": "backend"})
+ assert resp.status_code == 422
+
+ @pytest.mark.asyncio
+ async def test_no_enricher(self) -> None:
+ """Workspace mode with no contract data is a 404, not an empty detail."""
+ app = _make_workspace_app(ws_config=_make_ws_config())
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
+ resp = await c.get(
+ "/api/workspace/contracts/detail",
+ params={"repo": "backend", "file": "routes.py", "id": "http::GET::/api/users"},
+ )
+ assert resp.status_code == 404
+
+
# ---------------------------------------------------------------------------
# Tests — GET /api/workspace/co-changes
# ---------------------------------------------------------------------------