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(contracts): generate the TypeScript HTTP contract from the FastAPI schema (#2035)

Raghav Chamadiya361a7647337f
diff --git a/.gitattributes b/.gitattributes
index 41806c2f5..b6a94f2f9 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -3,3 +3,8 @@
# "#!/bin/bash\r" shebang that Linux cannot resolve, causing:
# exec /app/entrypoint.sh: no such file or directory
*.sh text eol=lf
+
+# Generated TypeScript is written with LF and diffed byte-for-byte by CI.
+# Without this, a Windows checkout rewrites it to CRLF and every local
+# regeneration reads as drift against what CI produces on Linux.
+packages/types/src/generated/*.ts text eol=lf
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7eb5e64ab..426be29ce 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -126,6 +126,10 @@ jobs:
- name: Test api-client
run: npm run test --workspace @repowise-dev/api-client
+ # Compiles the generated HTTP contract too, which nothing else imports yet.
+ - name: Type check types
+ run: npm run type-check --workspace @repowise-dev/types
+
- name: Test types
run: npm run test --workspace @repowise-dev/types
diff --git a/.github/workflows/publish-internal.yml b/.github/workflows/publish-internal.yml
index c3b540040..4f9496265 100644
--- a/.github/workflows/publish-internal.yml
+++ b/.github/workflows/publish-internal.yml
@@ -1,11 +1,13 @@
name: Publish internal prereleases
-# Publishes @repowise-dev/types and @repowise-dev/ui to GitHub Packages on
+# Publishes @repowise-dev/types, @repowise-dev/ui and @repowise-dev/api-client
+# to GitHub Packages on
# every push to `main`, tagged as `0.0.0-internal.<short-sha>`. Downstream
# consumers (e.g. hosted-frontend) pin to a specific SHA.
#
# Source package.json files declare the published names directly
-# (`@repowise-dev/types`, `@repowise-dev/ui`) but keep `private: true` and
+# (`@repowise-dev/types`, `@repowise-dev/ui`, `@repowise-dev/api-client`) but
+# keep `private: true` and
# `version: 0.0.1`. This workflow stamps the prerelease version and
# removes `private` only at publish time. The PyPI publish workflow
# (`publish.yml`) only fires on `v*` tags and is unaffected.
@@ -59,8 +61,10 @@ jobs:
run: |
npm run type-check --workspace @repowise-dev/types
npm run type-check --workspace @repowise-dev/ui
+ npm run type-check --workspace @repowise-dev/api-client
npm run test --workspace @repowise-dev/types
npm run test --workspace @repowise-dev/ui
+ npm run test --workspace @repowise-dev/api-client
- name: Compute prerelease version
id: ver
@@ -97,6 +101,29 @@ jobs:
npm publish
fi
+ # Published after ui: api-client depends on types at runtime and is
+ # built against ui, so a consumer resolving this SHA finds all three.
+ - name: Publish @repowise-dev/api-client
+ working-directory: packages/api-client
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN_GITHUB_PACKAGES }}
+ VERSION: ${{ steps.ver.outputs.version }}
+ run: |
+ npm pkg set version="$VERSION"
+ npm pkg set dependencies.@repowise-dev/types="$VERSION"
+ # ``./c4``, ``./graph`` and ``./hosted`` import types from ui, and the
+ # package ships raw TypeScript, so a consumer compiling it needs ui
+ # resolvable. It is a devDependency here because this repo builds
+ # against the workspace copy.
+ npm pkg delete devDependencies.@repowise-dev/ui
+ npm pkg set dependencies.@repowise-dev/ui="$VERSION"
+ npm pkg delete private
+ if npm view "@repowise-dev/api-client@$VERSION" version >/dev/null 2>&1; then
+ echo "@repowise-dev/api-client@$VERSION is already published, skipping"
+ else
+ npm publish
+ fi
+
- name: Summary
run: |
{
@@ -104,11 +131,13 @@ jobs:
echo ""
echo "- \`@repowise-dev/types@${{ steps.ver.outputs.version }}\`"
echo "- \`@repowise-dev/ui@${{ steps.ver.outputs.version }}\`"
+ echo "- \`@repowise-dev/api-client@${{ steps.ver.outputs.version }}\`"
echo ""
echo "Consumer install (hosted-frontend):"
echo ""
echo '```json'
echo '"@repowise-dev/types": "${{ steps.ver.outputs.version }}",'
- echo '"@repowise-dev/ui": "${{ steps.ver.outputs.version }}"'
+ echo '"@repowise-dev/ui": "${{ steps.ver.outputs.version }}",'
+ echo '"@repowise-dev/api-client": "${{ steps.ver.outputs.version }}"'
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
diff --git a/Makefile b/Makefile
index a2c5e924c..e693e4866 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,5 @@
.PHONY: install install-dev test test-unit test-integration test-e2e test-providers \
+ generate-types generate-types-check \
lint format typecheck clean build-web dev-web help
# ---------------------------------------------------------------------------
@@ -37,6 +38,12 @@ test-fast: ## Run unit + provider tests (fast, no fixtures needed)
# Code Quality
# ---------------------------------------------------------------------------
+generate-types: ## Regenerate the TypeScript HTTP contract from the FastAPI schema
+ uv run python scripts/generate_http_types.py
+
+generate-types-check: ## Fail if the generated HTTP contract is stale
+ uv run python scripts/generate_http_types.py --check
+
lint: ## Run ruff linter
uv run ruff check packages/ tests/
diff --git a/packages/api-client/src/package-exports.test.ts b/packages/api-client/src/package-exports.test.ts
new file mode 100644
index 000000000..08f588b4b
--- /dev/null
+++ b/packages/api-client/src/package-exports.test.ts
@@ -0,0 +1,31 @@
+// The export map is the published contract. `./hosted` in particular is
+// consumed only from outside this repo, so nothing else in here would fail if
+// a packaging change dropped it.
+import { existsSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { describe, expect, it } from "vitest";
+
+import manifest from "../package.json" with { type: "json" };
+
+const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+const exportMap = manifest.exports as Record<string, string>;
+
+describe("published export map", () => {
+ it("keeps the hosted provider reachable", () => {
+ expect(exportMap["./hosted"]).toBe("./src/hosted.ts");
+ });
+
+ it("points every subpath at a file that exists", () => {
+ const missing = Object.entries(exportMap).filter(
+ ([, target]) => !existsSync(join(packageRoot, target)),
+ );
+ expect(missing).toEqual([]);
+ });
+
+ it("is published under the scope the workflow authenticates against", () => {
+ expect(manifest.name).toBe("@repowise-dev/api-client");
+ expect(manifest.publishConfig?.registry).toBe("https://npm.pkg.github.com");
+ });
+});
diff --git a/packages/core/src/repowise/core/analysis/external_systems/__init__.py b/packages/core/src/repowise/core/analysis/external_systems/__init__.py
index a11c366b3..81eadaf61 100644
--- a/packages/core/src/repowise/core/analysis/external_systems/__init__.py
+++ b/packages/core/src/repowise/core/analysis/external_systems/__init__.py
@@ -12,8 +12,17 @@ The server layer keeps the queries; it fetches rows and hands them here.
from __future__ import annotations
+from .links import (
+ EXTERNAL_NODE_PREFIX,
+ ExternalSystemLink,
+ build_declaration_index,
+ build_declaration_links,
+ declaration_name_candidates,
+ resolve_declaration,
+)
from .records import (
AUXILIARY_PREFIXES,
+ IMPORT_EDGE_TYPE,
Scope,
in_scope,
is_primary_path,
@@ -55,8 +64,11 @@ __all__ = [
"DEFAULT_RELATIONSHIP_NODE_LIMIT",
"DEFAULT_SUMMARY_LIMIT",
"EVIDENCE_TARGET_LIMIT",
+ "EXTERNAL_NODE_PREFIX",
"EXTERNAL_TARGET_LIMIT",
+ "IMPORT_EDGE_TYPE",
"SUMMARY_VERSION_LIMIT",
+ "ExternalSystemLink",
"GraphTarget",
"ImportingFile",
"ImportingFiles",
@@ -68,14 +80,18 @@ __all__ = [
"RelationshipGraph",
"RelationshipNode",
"Scope",
+ "build_declaration_index",
+ "build_declaration_links",
"build_importing_files",
"build_package_summary",
"build_registry",
"build_relationship_graph",
"community_key",
+ "declaration_name_candidates",
"in_scope",
"is_primary_path",
"package_key",
+ "resolve_declaration",
"resolve_targets",
"split_community_key",
"split_package_key",
diff --git a/packages/core/src/repowise/core/analysis/external_systems/links.py b/packages/core/src/repowise/core/analysis/external_systems/links.py
new file mode 100644
index 000000000..1acbc4950
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/external_systems/links.py
@@ -0,0 +1,138 @@
+"""The declaration-to-external-node match, as a fold over plain records.
+
+The folds in :mod:`.summary` and :mod:`.relationships` take links as given, but
+only the persistence layer knew how to build one, so a consumer holding
+declarations and graph nodes could not reach them without a database. The
+matcher lives here, framework-free, and the CRUD writer calls it too, so the
+stored ``external_system_id`` and a link built from plain records cannot
+disagree about what resolves.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from dataclasses import dataclass
+from typing import Any
+
+from .records import field, package_key
+
+#: Graph nodes standing for a third-party package carry this ``node_id`` prefix.
+EXTERNAL_NODE_PREFIX = "external:"
+
+
+@dataclass(frozen=True, slots=True)
+class ExternalSystemLink:
+ """One external graph node resolved to the package a manifest declared."""
+
+ node_id: str
+ ecosystem: str
+ name: str
+
+ def as_dict(self) -> dict[str, Any]:
+ return {"node_id": self.node_id, "ecosystem": self.ecosystem, "name": self.name}
+
+
+def declaration_name_candidates(external_name: str) -> tuple[str, ...]:
+ """Declaration names to try for one node suffix, most precise first.
+
+ Resolver output is ecosystem-shaped (npm subpaths, Rust ``::`` paths,
+ Python dotted modules), so the declared package is a prefix of the node
+ rather than the whole of it.
+ """
+ candidates = [external_name]
+ if external_name.startswith("@"):
+ parts = external_name.split("/")
+ if len(parts) >= 2:
+ candidates.append("/".join(parts[:2]))
+ for separator in ("::", ".", "/"):
+ if separator in external_name:
+ candidates.append(external_name.split(separator, 1)[0])
+ return tuple(dict.fromkeys(candidate for candidate in candidates if candidate))
+
+
+def build_declaration_index(
+ declarations: Iterable[Any],
+) -> dict[str, tuple[str, str] | None]:
+ """Index declarations by the names a node suffix can match them under.
+
+ A bare name maps to ``None`` once two ecosystems declare it, so an
+ ambiguous target stays unlinked rather than resolving to whichever
+ manifest was read first. Ecosystem-qualified keys stay resolvable either
+ way.
+
+ An absent ecosystem counts as one: the test is ``previous is None``, not
+ ``if not previous``, so a name declared once without an ecosystem and once
+ with one is ambiguous. The CRUD writer builds its id map from this index,
+ so relaxing that here changes what gets stored.
+ """
+ index: dict[str, tuple[str, str] | None] = {}
+ ecosystem_of: dict[str, str] = {}
+ for declaration in declarations:
+ name = field(declaration, "name", "") or ""
+ ecosystem = field(declaration, "ecosystem", "") or ""
+ if not name:
+ continue
+ identity = (ecosystem, name)
+ if ecosystem:
+ index.setdefault(package_key(ecosystem, name), identity)
+ previous = ecosystem_of.get(name)
+ if previous is None:
+ ecosystem_of[name] = ecosystem
+ index[name] = identity
+ elif previous != ecosystem:
+ index[name] = None
+ return index
+
+
+def resolve_declaration(
+ node_id: str,
+ index: dict[str, tuple[str, str] | None],
+) -> tuple[str, str] | None:
+ """The package one external node stands for, or ``None`` if unresolved.
+
+ The first candidate the index knows wins even when it is ambiguous; falling
+ through to a broader candidate would resolve exactly the collision the
+ ambiguous entry exists to refuse.
+ """
+ if not node_id.startswith(EXTERNAL_NODE_PREFIX):
+ return None
+ suffix = node_id[len(EXTERNAL_NODE_PREFIX) :]
+ for candidate in declaration_name_candidates(suffix):
+ if candidate in index:
+ return index[candidate]
+ return None
+
+
+def build_declaration_links(
+ declarations: Iterable[Any],
+ external_nodes: Iterable[Any],
+) -> list[ExternalSystemLink]:
+ """Link every external graph node that resolves to a declared package.
+
+ Unresolved and ambiguous nodes are omitted rather than carried as holes,
+ which is the same set the stored ``external_system_id`` leaves null.
+
+ The folds this feeds also take import edges, and expect them already
+ narrowed to :data:`~.records.IMPORT_EDGE_TYPE` — an unfiltered edge list
+ counts calls as package usage.
+ """
+ index = build_declaration_index(declarations)
+ links: list[ExternalSystemLink] = []
+ for node in external_nodes:
+ node_id = field(node, "node_id", "") or ""
+ identity = resolve_declaration(node_id, index)
+ if identity is None:
+ continue
+ ecosystem, name = identity
+ links.append(ExternalSystemLink(node_id=node_id, ecosystem=ecosystem, name=name))
+ return links
+
+
+__all__ = [
+ "EXTERNAL_NODE_PREFIX",
+ "ExternalSystemLink",
+ "build_declaration_index",
+ "build_declaration_links",
+ "declaration_name_candidates",
+ "resolve_declaration",
+]
diff --git a/packages/core/src/repowise/core/analysis/external_systems/records.py b/packages/core/src/repowise/core/analysis/external_systems/records.py
index 580c85665..4fd9a717d 100644
--- a/packages/core/src/repowise/core/analysis/external_systems/records.py
+++ b/packages/core/src/repowise/core/analysis/external_systems/records.py
@@ -25,6 +25,12 @@ Scope = Literal["primary", "all"]
AUXILIARY_PREFIXES = (".claude/worktrees/", "local-stash/")
+#: The only edge type that counts as declared-package usage. The relationship
+#: folds additionally expect file sources; both rules are applied by whoever
+#: fetches the edges, not by the folds.
+IMPORT_EDGE_TYPE = "imports"
+
+
def is_primary_path(path: str | None) -> bool:
"""Whether a declaration or importing file belongs to the repository proper."""
return not (path or "").startswith(AUXILIARY_PREFIXES)
@@ -61,6 +67,7 @@ def target_basis(node_id: str, package_name: str) -> Literal["exact", "subpath",
__all__ = [
"AUXILIARY_PREFIXES",
+ "IMPORT_EDGE_TYPE",
"Scope",
"field",
"in_scope",
diff --git a/packages/core/src/repowise/core/persistence/crud/external_systems.py b/packages/core/src/repowise/core/persistence/crud/external_systems.py
index 70633984b..d3ace4805 100644
--- a/packages/core/src/repowise/core/persistence/crud/external_systems.py
+++ b/packages/core/src/repowise/core/persistence/crud/external_systems.py
@@ -114,7 +114,16 @@ async def link_graph_nodes_to_external_systems(
"""
if not name_to_id:
return 0
- prefix = "external:"
+
+ # Imported inside the function, not at module scope: the matcher's package
+ # reaches this module back through ``analysis.health``, which loads the
+ # analyzer engine on import.
+ from repowise.core.analysis.external_systems.links import (
+ EXTERNAL_NODE_PREFIX,
+ declaration_name_candidates,
+ )
+
+ prefix = EXTERNAL_NODE_PREFIX
result = await session.execute(
select(GraphNode).where(
GraphNode.repository_id == repository_id,
@@ -124,9 +133,12 @@ async def link_graph_nodes_to_external_systems(
updated = 0
for node in result.scalars():
suffix = node.node_id[len(prefix) :]
- # Try exact and ecosystem-shaped package candidates in priority order.
sys_id = next(
- (name_to_id[name] for name in _external_name_candidates(suffix) if name in name_to_id),
+ (
+ name_to_id[name]
+ for name in declaration_name_candidates(suffix)
+ if name in name_to_id
+ ),
None,
)
if node.external_system_id != sys_id:
@@ -136,47 +148,38 @@ async def link_graph_nodes_to_external_systems(
return updated
-def _external_name_candidates(external_name: str) -> tuple[str, ...]:
- """Return declaration names to try, ordered from precise to broad.
-
- Resolver output is ecosystem-shaped (npm subpaths, Rust ``::`` paths,
- Python dotted modules). Keeping normalization in this small pure function
- makes another ecosystem a local extension without another graph traversal.
- """
- candidates = [external_name]
- if external_name.startswith("@"):
- parts = external_name.split("/")
- if len(parts) >= 2:
- candidates.append("/".join(parts[:2]))
- for separator in ("::", ".", "/"):
- if separator in external_name:
- candidates.append(external_name.split(separator, 1)[0])
- return tuple(dict.fromkeys(candidate for candidate in candidates if candidate))
-
-
def build_external_system_link_map(
systems: list[dict],
id_map: dict[tuple[str, str], int],
) -> dict[str, int | None]:
- """Build exact/prefixed link keys while preserving name ambiguity."""
- links: dict[str, int | None] = {}
- name_ecosystems: dict[str, str] = {}
- for system in systems:
- name = system.get("name", "")
- declared_in = system.get("declared_in", "")
- ecosystem = system.get("ecosystem", "")
- system_id = id_map.get((name, declared_in))
- if not name or system_id is None:
- continue
- if ecosystem:
- links.setdefault(f"{ecosystem}:{name}", system_id)
- previous_ecosystem = name_ecosystems.get(name)
- if previous_ecosystem is None:
- name_ecosystems[name] = ecosystem
- links[name] = system_id
- elif previous_ecosystem != ecosystem:
- links[name] = None
- return links
+ """Build exact/prefixed link keys while preserving name ambiguity.
+
+ The ambiguity rule itself lives in ``analysis.external_systems.links`` and
+ is shared with the plain-record path, so the stored ``external_system_id``
+ and a link built without a database cannot disagree about what resolves.
+ Declarations whose row was not persisted are dropped before indexing: they
+ have no id to resolve to, and letting one poison a bare name would refuse a
+ target the old map linked.
+ """
+ from repowise.core.analysis.external_systems.links import build_declaration_index
+
+ persisted = [
+ system
+ for system in systems
+ if system.get("name")
+ and id_map.get((system.get("name", ""), system.get("declared_in", ""))) is not None
+ ]
+ # First row wins per identity, matching the insertion order the map is built in.
+ first_id: dict[tuple[str, str], int] = {}
+ for system in persisted:
+ identity = (system.get("ecosystem", ""), system.get("name", ""))
+ first_id.setdefault(
+ identity, id_map[(system.get("name", ""), system.get("declared_in", ""))]
+ )
+ return {
+ key: (None if identity is None else first_id.get(identity))
+ for key, identity in build_declaration_index(persisted).items()
+ }
async def list_external_systems(session: AsyncSession, repository_id: str) -> list[ExternalSystem]:
diff --git a/packages/core/src/repowise/core/workspace/diagnostics.py b/packages/core/src/repowise/core/workspace/diagnostics.py
index f0f598c6c..de2ddb487 100644
--- a/packages/core/src/repowise/core/workspace/diagnostics.py
+++ b/packages/core/src/repowise/core/workspace/diagnostics.py
@@ -57,6 +57,15 @@ class UnmatchedReason:
EXTERNAL_HOST = "external_host"
+#: The closed set, for the wire copies that have to agree with it.
+UNMATCHED_REASON_VALUES = (
+ UnmatchedReason.NO_PROVIDER,
+ UnmatchedReason.INTERNAL_ONLY,
+ UnmatchedReason.UNLINKED,
+ UnmatchedReason.EXTERNAL_HOST,
+)
+
+
# ---------------------------------------------------------------------------
# Data models
# ---------------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.py
index 5de0950fa..e65bf62ef 100644
--- a/packages/server/src/repowise/server/routers/chat.py
+++ b/packages/server/src/repowise/server/routers/chat.py
@@ -36,11 +36,14 @@ from repowise.server.deps import (
from repowise.server.provider_config import get_chat_provider_instance
from repowise.server.schemas import (
ArtifactUpdateRequest,
+ ChatArtifactEnvelope,
ChatMessageResponse,
ChatRequest,
+ ConversationDetailResponse,
ConversationForkRequest,
ConversationResponse,
ConversationUpdateRequest,
+ OkResponse,
)
logger = logging.getLogger(__name__)
@@ -483,7 +486,7 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):
# ---------------------------------------------------------------------------
[email protected]("/api/repos/{repo_id}/chat/conversations")
[email protected]("/api/repos/{repo_id}/chat/conversations", response_model=list[ConversationResponse])
async def list_conversations(
repo_id: str,
session=Depends(get_db_session),
@@ -496,7 +499,7 @@ async def list_conversations(
return result
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}")
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}", response_model=ConversationDetailResponse)
async def get_conversation(
repo_id: str,
conversation_id: str,
@@ -513,7 +516,10 @@ async def get_conversation(
}
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}/artifacts/{artifact_id}")
+ "/api/repos/{repo_id}/chat/conversations/{conversation_id}/artifacts/{artifact_id}",
+ response_model=ChatArtifactEnvelope,
+)
async def get_conversation_artifact(
repo_id: str,
conversation_id: str,
@@ -541,7 +547,10 @@ async def get_conversation_artifact(
raise HTTPException(404, "Artifact not found")
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}/artifacts/{artifact_id}")
+ "/api/repos/{repo_id}/chat/conversations/{conversation_id}/artifacts/{artifact_id}",
+ response_model=ChatArtifactEnvelope,
+)
async def update_conversation_artifact(
repo_id: str,
conversation_id: str,
@@ -579,7 +588,7 @@ async def update_conversation_artifact(
raise HTTPException(404, "Artifact not found")
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}")
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}", response_model=OkResponse)
async def delete_conversation(
repo_id: str,
conversation_id: str,
@@ -592,7 +601,7 @@ async def delete_conversation(
return {"ok": True}
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}/restore")
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}/restore", response_model=ConversationResponse)
async def restore_conversation(repo_id: str, conversation_id: str, session=Depends(get_db_session)):
conv = await crud.get_conversation(session, conversation_id)
if not conv or conv.repository_id != repo_id:
@@ -601,7 +610,7 @@ async def restore_conversation(repo_id: str, conversation_id: str, session=Depen
return ConversationResponse.from_orm(restored)
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}")
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}", response_model=ConversationResponse)
async def update_conversation(
repo_id: str,
conversation_id: str,
@@ -621,7 +630,7 @@ async def update_conversation(
return ConversationResponse.from_orm(conv)
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}/fork")
[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}/fork", response_model=ConversationResponse)
async def fork_conversation(
repo_id: str,
conversation_id: str,
diff --git a/packages/server/src/repowise/server/routers/claude_md.py b/packages/server/src/repowise/server/routers/claude_md.py
index 333c439bf..c40e507b3 100644
--- a/packages/server/src/repowise/server/routers/claude_md.py
+++ b/packages/server/src/repowise/server/routers/claude_md.py
@@ -10,6 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.generation.editor_files import ClaudeMdGenerator, EditorFileDataFetcher
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.schemas import ClaudeMdGenerateResponse, ClaudeMdResponse
router = APIRouter(
tags=["claude-md"],
@@ -17,7 +18,7 @@ router = APIRouter(
)
[email protected]("/api/repos/{repo_id}/claude-md")
[email protected]("/api/repos/{repo_id}/claude-md", response_model=ClaudeMdResponse)
async def get_claude_md(
repo_id: str,
session: AsyncSession = Depends(get_db_session),
@@ -45,7 +46,11 @@ async def get_claude_md(
}
[email protected]("/api/repos/{repo_id}/claude-md/generate", status_code=202)
+ "/api/repos/{repo_id}/claude-md/generate",
+ response_model=ClaudeMdGenerateResponse,
+ status_code=202,
+)
async def generate_claude_md(
repo_id: str,
session: AsyncSession = Depends(get_db_session),
diff --git a/packages/server/src/repowise/server/routers/code_health/badge.py b/packages/server/src/repowise/server/routers/code_health/badge.py
index a078ff24b..13ea25aed 100644
--- a/packages/server/src/repowise/server/routers/code_health/badge.py
+++ b/packages/server/src/repowise/server/routers/code_health/badge.py
@@ -8,6 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.grading import band_for
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session
+from repowise.server.schemas import HealthBadgeResponse
from ._router import router
@@ -94,7 +95,7 @@ async def _badge_average_health(session: AsyncSession, repo_id: str) -> float |
return 10.0 if avg is None else avg
[email protected]("/api/repos/{repo_id}/health/badge.json")
[email protected]("/api/repos/{repo_id}/health/badge.json", response_model=HealthBadgeResponse)
async def health_badge_json(
repo_id: str,
session: AsyncSession = Depends(get_db_session),
diff --git a/packages/server/src/repowise/server/routers/code_health/churn_routes.py b/packages/server/src/repowise/server/routers/code_health/churn_routes.py
index 6d30dd866..91b4c910e 100644
--- a/packages/server/src/repowise/server/routers/code_health/churn_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/churn_routes.py
@@ -8,12 +8,16 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.churn_complexity import churn_complexity_points
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session
+from repowise.server.schemas import ChurnComplexityResponse
from ._router import router
from .serializers import _churn_complexity_to_dict
[email protected]("/api/repos/{repo_id}/health/churn-complexity")
+ "/api/repos/{repo_id}/health/churn-complexity",
+ response_model=ChurnComplexityResponse,
+)
async def churn_complexity(
repo_id: str,
# The ceiling has to clear the code-health map's file window (2,000), not
diff --git a/packages/server/src/repowise/server/routers/code_health/findings_routes.py b/packages/server/src/repowise/server/routers/code_health/findings_routes.py
index 45d50acc2..683ba9183 100644
--- a/packages/server/src/repowise/server/routers/code_health/findings_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/findings_routes.py
@@ -8,13 +8,20 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session
+from repowise.server.schemas import (
+ HealthFindingResponse,
+ HealthFindingWithSymbolResponse,
+)
from ._router import router
from .loaders import _attach_symbol_ids
from .serializers import _finding_to_dict
[email protected]("/api/repos/{repo_id}/health/findings")
+ "/api/repos/{repo_id}/health/findings",
+ response_model=list[HealthFindingWithSymbolResponse],
+)
async def list_health_findings(
repo_id: str,
biomarker_type: str | None = Query(None),
@@ -53,7 +60,10 @@ class FindingStatusUpdate(BaseModel):
_ALLOWED_STATUSES = {"open", "acknowledged", "resolved", "false_positive"}
[email protected]("/api/repos/{repo_id}/health/findings/{finding_id}")
+ "/api/repos/{repo_id}/health/findings/{finding_id}",
+ response_model=HealthFindingResponse,
+)
async def update_finding_status(
repo_id: str,
finding_id: str,
diff --git a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
index 4f336ba9e..0c7c59fd9 100644
--- a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
@@ -15,6 +15,7 @@ from repowise.core.analysis.health.models import primary_finding
from repowise.core.analysis.health.suggestions import suggestion_for as _suggestion_for
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session
+from repowise.server.schemas import HealthWorkQueueResponse
from ._router import router
@@ -50,7 +51,10 @@ def _effort_for_nloc(nloc: int) -> str:
return "XL"
[email protected]("/api/repos/{repo_id}/health/refactoring-targets")
+ "/api/repos/{repo_id}/health/refactoring-targets",
+ response_model=HealthWorkQueueResponse,
+)
async def health_work_queue(
repo_id: str,
limit: int = Query(200, ge=1, le=500),
diff --git a/packages/server/src/repowise/server/routers/code_health/trends_routes.py b/packages/server/src/repowise/server/routers/code_health/trends_routes.py
index 6c73beb1c..17dc9747a 100644
--- a/packages/server/src/repowise/server/routers/code_health/trends_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/trends_routes.py
@@ -10,6 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.trends import diff_snapshots, file_trend, recent_kpis
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session
+from repowise.server.schemas import FileHealthTrendResponse, HealthTrendResponse
from ._router import router
from .serializers import _file_trend_to_dict
@@ -19,7 +20,10 @@ from .serializers import _file_trend_to_dict
FILE_DELTA_LIMIT: int = 50
[email protected]("/api/repos/{repo_id}/health/files/trend")
+ "/api/repos/{repo_id}/health/files/trend",
+ response_model=FileHealthTrendResponse,
+)
async def file_health_trend(
repo_id: str,
file_path: str = Query(..., description="File path to chart over time"),
@@ -36,7 +40,7 @@ async def file_health_trend(
return _file_trend_to_dict(file_trend(snapshots, file_path))
[email protected]("/api/repos/{repo_id}/health/trend")
[email protected]("/api/repos/{repo_id}/health/trend", response_model=HealthTrendResponse)
async def health_trend(
repo_id: str,
limit: int = Query(20, ge=1, le=50),
diff --git a/packages/server/src/repowise/server/routers/dead_code.py b/packages/server/src/repowise/server/routers/dead_code.py
index 4488e790b..a5a16dce4 100644
--- a/packages/server/src/repowise/server/routers/dead_code.py
+++ b/packages/server/src/repowise/server/routers/dead_code.py
@@ -12,6 +12,7 @@ from repowise.core.analysis.dead_code.risk_factors import (
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.schemas import (
+ DeadCodeAnalyzeResponse,
DeadCodeFindingResponse,
DeadCodePatchRequest,
DeadCodeSummaryResponse,
@@ -53,7 +54,11 @@ async def list_dead_code(
return [DeadCodeFindingResponse.from_orm(f) for f in findings[:limit]]
[email protected]("/api/repos/{repo_id}/dead-code/analyze", status_code=202)
+ "/api/repos/{repo_id}/dead-code/analyze",
+ response_model=DeadCodeAnalyzeResponse,
+ status_code=202,
+)
async def analyze_dead_code(
repo_id: str,
request: Request,
diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.py
index 40a5a8c54..8d4336431 100644
--- a/packages/server/src/repowise/server/routers/decisions.py
+++ b/packages/server/src/repowise/server/routers/decisions.py
@@ -13,11 +13,14 @@ from repowise.server.schemas import (
DecisionCodeEdge,
DecisionCountsResponse,
DecisionCreate,
+ DecisionEvidenceListResponse,
DecisionEvidenceResponse,
DecisionGraphEdge,
DecisionGraphNode,
DecisionGraphResponse,
+ DecisionHealthResponse,
DecisionLineageEntry,
+ DecisionLineageResponse,
DecisionRecordResponse,
DecisionStatusUpdate,
)
@@ -107,6 +110,7 @@ async def list_decisions(
@router.get(
"/api/repos/{repo_id}/decisions/health",
+ response_model=DecisionHealthResponse,
)
async def decision_health(
repo_id: str,
@@ -230,6 +234,7 @@ async def get_decision(
@router.get(
"/api/repos/{repo_id}/decisions/{decision_id}/evidence",
+ response_model=DecisionEvidenceListResponse,
)
async def list_decision_evidence(
repo_id: str,
@@ -252,6 +257,7 @@ async def list_decision_evidence(
@router.get(
"/api/repos/{repo_id}/decisions/{decision_id}/lineage",
+ response_model=DecisionLineageResponse,
)
async def get_decision_lineage(
repo_id: str,
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index 4e26d6f85..e17f695c3 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -47,6 +47,7 @@ from repowise.server.schemas import (
AgentTrendBucket,
AgentTrendResponse,
ChangeFeaturesResponse,
+ CoChangeResponse,
CommitDetailResponse,
CommitEvolutionBucket,
CommitEvolutionResponse,
@@ -597,7 +598,7 @@ async def get_ownership(
)
[email protected]("/{repo_id}/co-changes")
[email protected]("/{repo_id}/co-changes", response_model=CoChangeResponse)
async def get_co_changes(
repo_id: str,
file_path: str = Query(..., description="Relative file path"),
diff --git a/packages/server/src/repowise/server/routers/graph/path.py b/packages/server/src/repowise/server/routers/graph/path.py
index 4c197afc8..642755404 100644
--- a/packages/server/src/repowise/server/routers/graph/path.py
+++ b/packages/server/src/repowise/server/routers/graph/path.py
@@ -10,11 +10,17 @@ from repowise.core.ingestion.models import TEMPORAL_EDGE_TYPES
from repowise.core.persistence.models import GraphEdge, GraphNode
from repowise.server.deps import get_db_session
from repowise.server.routers.graph._common import with_repo
+from repowise.server.schemas import DependencyPathResponse
router = APIRouter()
[email protected]("/{repo_id}/path")
+ "/{repo_id}/path",
+ response_model=DependencyPathResponse,
+ # ``visual_context`` is only built when no path exists.
+ response_model_exclude_unset=True,
+)
async def dependency_path(
repo_id: str,
source: str = Query(..., alias="from", description="Source node ID"),
diff --git a/packages/server/src/repowise/server/routers/pages.py b/packages/server/src/repowise/server/routers/pages.py
index 59994cee9..9f4a45840 100644
--- a/packages/server/src/repowise/server/routers/pages.py
+++ b/packages/server/src/repowise/server/routers/pages.py
@@ -21,6 +21,7 @@ from repowise.core.persistence import crud
from repowise.core.persistence.models import _now_utc
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.schemas import (
+ JobAcceptedResponse,
PageResponse,
PageSummaryResponse,
PageVersionResponse,
@@ -233,7 +234,7 @@ async def update_page_notes(
return PageResponse.from_orm(page)
[email protected]("/lookup/regenerate", status_code=202)
[email protected]("/lookup/regenerate", response_model=JobAcceptedResponse, status_code=202)
async def regenerate_page_by_query(
request: Request,
page_id: str = Query(..., description="Page ID"),
diff --git a/packages/server/src/repowise/server/routers/providers.py b/packages/server/src/repowise/server/routers/providers.py
index f2eeef0b8..8d56ec38b 100644
--- a/packages/server/src/repowise/server/routers/providers.py
+++ b/packages/server/src/repowise/server/routers/providers.py
@@ -12,7 +12,12 @@ from repowise.server.provider_config import (
set_active_provider,
set_api_key,
)
-from repowise.server.schemas import SetActiveProviderRequest, SetApiKeyRequest
+from repowise.server.schemas import (
+ ProviderStatusResponse,
+ ProviderValidationResponse,
+ SetActiveProviderRequest,
+ SetApiKeyRequest,
+)
router = APIRouter(
prefix="/api/providers",
@@ -45,7 +50,7 @@ async def _repo_path_for(request: Request, repo_id: str | None) -> str | None:
return None
[email protected]("", response_model=ProviderStatusResponse)
async def get_providers(request: Request, repo_id: str | None = None):
"""List all providers with their status and active selection.
@@ -57,7 +62,7 @@ async def get_providers(request: Request, repo_id: str | None = None):
return list_provider_status(repo_id=repo_id, repo_path=repo_path)
[email protected]("/active", response_model=ProviderStatusResponse)
async def set_active(body: SetActiveProviderRequest, request: Request):
"""Set the active provider and model (per-repo when ``repo_id`` is given)."""
try:
@@ -100,7 +105,7 @@ async def remove_provider_key(
raise HTTPException(400, str(exc)) from exc
[email protected]("/{provider_id}/validate")
[email protected]("/{provider_id}/validate", response_model=ProviderValidationResponse)
async def validate_provider(
provider_id: str,
request: Request,
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
index 1697c95d3..79e03b298 100644
--- a/packages/server/src/repowise/server/routers/refactoring.py
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -27,6 +27,13 @@ from repowise.core.analysis.health.refactoring.recommendations import (
from repowise.core.persistence import crud
from repowise.core.persistence.crud.analysis.refactoring import ALLOWED_STATUSES
from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.schemas import (
+ RefactoringOpportunitiesResponse,
+ RefactoringOpportunityDetailResponse,
+ RefactoringOpportunityStatusResponse,
+ RefactoringPlanStatusResponse,
+ RefactoringRollupResponse,
+)
from repowise.server.services.refactoring_health import (
CANONICAL_ORDERS,
CANONICAL_VIEWS,
@@ -392,7 +399,13 @@ def _service(session: AsyncSession, repo_id: str) -> RefactoringHealthService:
return RefactoringHealthService(session, repo_id, repo_id)
[email protected]("/{repo_id}/refactoring/opportunities")
+ "/{repo_id}/refactoring/opportunities",
+ response_model=RefactoringOpportunitiesResponse,
+ # ``ignored_arguments`` is only present when the query dropped something;
+ # a default would put an empty object on every response.
+ response_model_exclude_unset=True,
+)
async def get_refactoring_opportunities(
repo_id: str,
refactoring_type: str | None = Query(
@@ -458,7 +471,7 @@ async def get_refactoring_opportunities(
return body
[email protected]("/{repo_id}/refactoring/summary")
[email protected]("/{repo_id}/refactoring/summary", response_model=RefactoringRollupResponse)
async def get_refactoring_rollup(
repo_id: str,
session: AsyncSession = Depends(get_db_session),
@@ -468,7 +481,11 @@ async def get_refactoring_rollup(
return {"summary": await service.summary(), "directive": await service.directive()}
[email protected]("/{repo_id}/refactoring/opportunities/{opportunity_id}")
+ "/{repo_id}/refactoring/opportunities/{opportunity_id}",
+ response_model=RefactoringOpportunityDetailResponse,
+ response_model_exclude_unset=True,
+)
async def get_refactoring_opportunity_detail(
repo_id: str,
opportunity_id: str,
@@ -497,7 +514,10 @@ class RefactoringOpportunityStatusUpdate(BaseModel):
status: str = Field(..., description="open | acknowledged | resolved | false_positive")
[email protected]("/{repo_id}/refactoring/opportunities/{opportunity_id}/status")
+ "/{repo_id}/refactoring/opportunities/{opportunity_id}/status",
+ response_model=RefactoringOpportunityStatusResponse,
+)
async def update_refactoring_opportunity_state(
repo_id: str,
opportunity_id: str,
@@ -614,7 +634,10 @@ class RefactoringStatusUpdate(BaseModel):
status: str = Field(..., description="open | acknowledged | resolved | false_positive")
[email protected]("/{repo_id}/refactoring/{suggestion_id}/status")
+ "/{repo_id}/refactoring/{suggestion_id}/status",
+ response_model=RefactoringPlanStatusResponse,
+)
async def update_refactoring_plan_status(
repo_id: str,
suggestion_id: str,
diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.py
index 2b097f4fa..e79e443e9 100644
--- a/packages/server/src/repowise/server/routers/repos.py
+++ b/packages/server/src/repowise/server/routers/repos.py
@@ -34,7 +34,9 @@ from repowise.server.job_executor import execute_job
from repowise.server.mcp_server._meta import read_live_head, resolve_indexed_commit
from repowise.server.routers._sorting import repository_sort_key
from repowise.server.schemas import (
+ JobAcceptedResponse,
RepoCreate,
+ RepoDeletedResponse,
RepoResponse,
ReposSummaryResponse,
RepoStatsResponse,
@@ -536,7 +538,7 @@ async def update_repo(
return RepoResponse.from_orm(repo)
[email protected]("/{repo_id}")
[email protected]("/{repo_id}", response_model=RepoDeletedResponse)
async def delete_repo(
repo_id: str,
request: Request,
@@ -655,7 +657,7 @@ async def get_repo_stats(
)
-def _accepted(job_id: str) -> dict:
+def _accepted(job_id: str) -> JobAcceptedResponse:
"""Standard 202 launch payload, carrying a stream token for the new job.
The token lets a client stream ``/api/jobs/{id}/stream`` immediately without
@@ -663,7 +665,7 @@ def _accepted(job_id: str) -> dict:
"""
from repowise.server.stream_auth import mint_stream_token
- return {"job_id": job_id, "status": "accepted", "stream_token": mint_stream_token(job_id)}
+ return JobAcceptedResponse(job_id=job_id, stream_token=mint_stream_token(job_id))
async def _ensure_no_active_job(session: AsyncSession, repo_id: str) -> None:
@@ -685,7 +687,7 @@ async def _ensure_no_active_job(session: AsyncSession, repo_id: str) -> None:
)
[email protected]("/{repo_id}/sync", status_code=202)
[email protected]("/{repo_id}/sync", response_model=JobAcceptedResponse, status_code=202)
async def sync_repo(
repo_id: str,
request: Request,
@@ -715,7 +717,7 @@ async def sync_repo(
return _accepted(job.id)
[email protected]("/{repo_id}/full-resync", status_code=202)
[email protected]("/{repo_id}/full-resync", response_model=JobAcceptedResponse, status_code=202)
async def full_resync(
repo_id: str,
request: Request,
@@ -870,7 +872,7 @@ def _generate_job_config(body: GenerateRequestBody) -> dict:
return config
[email protected]("/{repo_id}/generate", status_code=202)
[email protected]("/{repo_id}/generate", response_model=JobAcceptedResponse, status_code=202)
async def generate_pages(
repo_id: str,
request: Request,
@@ -1014,7 +1016,7 @@ async def generate_estimate(
}
[email protected]("/{repo_id}/index", status_code=202)
[email protected]("/{repo_id}/index", response_model=JobAcceptedResponse, status_code=202)
async def index_repo(
repo_id: str,
request: Request,
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index bceee8f3a..edc6b445c 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -39,6 +39,7 @@ from repowise.server.schemas import (
WorkspaceGraphResponse,
WorkspaceRepoEntry,
WorkspaceResponse,
+ WorkspaceSyncResponse,
WorkspaceSystemGraphResponse,
)
from repowise.server.services.module_health import read_repo_health_score
@@ -848,7 +849,7 @@ async def get_architecture(
# ---------------------------------------------------------------------------
[email protected]("/sync", status_code=202)
[email protected]("/sync", response_model=WorkspaceSyncResponse, status_code=202)
async def sync_workspace(
request: Request,
repo_alias: str | None = Query(
@@ -868,10 +869,7 @@ async def sync_workspace(
scheduler, cost ledger, and live-progress hooks all work without
special cases.
"""
- from repowise.server.schemas import (
- WorkspaceSyncResponse,
- WorkspaceSyncResult,
- )
+ from repowise.server.schemas import WorkspaceSyncResult
_require_workspace(ws_config)
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index d188ab51f..a628c7e20 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -36,13 +36,33 @@ from .c4 import (
)
from .chat import (
ArtifactUpdateRequest,
+ ChatArtifactEnvelope,
ChatMessageResponse,
ChatRequest,
+ ConversationDetailResponse,
ConversationForkRequest,
ConversationResponse,
ConversationUpdateRequest,
)
+from .claude_md import ClaudeMdGenerateResponse, ClaudeMdResponse
+from .code_health import (
+ ChurnComplexityPoint,
+ ChurnComplexityResponse,
+ FileHealthTrendResponse,
+ FileTrendPointResponse,
+ HealthBadgeResponse,
+ HealthFileDelta,
+ HealthFindingResponse,
+ HealthFindingWithSymbolResponse,
+ HealthTrendAlert,
+ HealthTrendKpiRow,
+ HealthTrendResponse,
+ HealthTrendSummary,
+ HealthWorkItem,
+ HealthWorkQueueResponse,
+)
from .code_quality import (
+ DeadCodeAnalyzeResponse,
DeadCodeFindingResponse,
DeadCodePatchRequest,
DeadCodeSummaryResponse,
@@ -58,11 +78,14 @@ from .decisions import (
DecisionCodeEdge,
DecisionCountsResponse,
DecisionCreate,
+ DecisionEvidenceListResponse,
DecisionEvidenceResponse,
DecisionGraphEdge,
DecisionGraphNode,
DecisionGraphResponse,
+ DecisionHealthResponse,
DecisionLineageEntry,
+ DecisionLineageResponse,
DecisionRecordResponse,
DecisionStatusUpdate,
)
@@ -80,6 +103,7 @@ from .git import (
AgentTrendBucket,
AgentTrendResponse,
ChangeFeaturesResponse,
+ CoChangeResponse,
CommitDetailResponse,
CommitEvolutionBucket,
CommitEvolutionResponse,
@@ -103,6 +127,7 @@ from .graph import (
CommunitySliceResponse,
DeadCodeGraphNodeResponse,
DeadCodeGraphResponse,
+ DependencyPathResponse,
EgoGraphResponse,
GraphEdgeResponse,
GraphExportResponse,
@@ -166,8 +191,17 @@ from .pages import (
PageVersionResponse,
)
from .pagination import Paginated
+from .refactoring import (
+ RefactoringOpportunitiesResponse,
+ RefactoringOpportunityDetailResponse,
+ RefactoringOpportunityStatusResponse,
+ RefactoringPlanStatusResponse,
+ RefactoringRollupResponse,
+)
from .repository import (
+ JobAcceptedResponse,
RepoCreate,
+ RepoDeletedResponse,
RepoResponse,
ReposSummaryResponse,
RepoSummaryRow,
@@ -182,11 +216,16 @@ from .symbols import (
SymbolResponse,
)
from .ui_helpers import (
+ ActiveProviderSelection,
CostGroupResponse,
CostSummaryResponse,
DistillSavingsGroup,
DistillSavingsResponse,
McpDropGroup,
+ OkResponse,
+ ProviderEntry,
+ ProviderStatusResponse,
+ ProviderValidationResponse,
SetActiveProviderRequest,
SetApiKeyRequest,
WebhookResponse,
@@ -232,6 +271,7 @@ from .zoom import (
)
__all__ = [
+ "ActiveProviderSelection",
"AgentTrendBucket",
"AgentTrendResponse",
"ArchEdgeResponse",
@@ -261,8 +301,14 @@ __all__ = [
"ChangelogEntryModel",
"ChangelogResponse",
"ChangelogSectionModel",
+ "ChatArtifactEnvelope",
"ChatMessageResponse",
"ChatRequest",
+ "ChurnComplexityPoint",
+ "ChurnComplexityResponse",
+ "ClaudeMdGenerateResponse",
+ "ClaudeMdResponse",
+ "CoChangeResponse",
"CochangeWarning",
"CommitDetailResponse",
"CommitEvolutionBucket",
@@ -274,6 +320,7 @@ __all__ = [
"CommunitySliceNodeResponse",
"CommunitySliceResponse",
"CommunitySummaryItem",
+ "ConversationDetailResponse",
"ConversationForkRequest",
"ConversationResponse",
"ConversationUpdateRequest",
@@ -283,6 +330,7 @@ __all__ = [
"CouplingEdgeResponse",
"CouplingGraphResponse",
"CouplingNodeResponse",
+ "DeadCodeAnalyzeResponse",
"DeadCodeFindingResponse",
"DeadCodeGraphNodeResponse",
"DeadCodeGraphResponse",
@@ -291,13 +339,17 @@ __all__ = [
"DecisionCodeEdge",
"DecisionCountsResponse",
"DecisionCreate",
+ "DecisionEvidenceListResponse",
"DecisionEvidenceResponse",
"DecisionGraphEdge",
"DecisionGraphNode",
"DecisionGraphResponse",
+ "DecisionHealthResponse",
"DecisionLineageEntry",
+ "DecisionLineageResponse",
"DecisionRecordResponse",
"DecisionStatusUpdate",
+ "DependencyPathResponse",
"DirectRiskEntry",
"DistillSavingsGroup",
"DistillSavingsResponse",
@@ -310,6 +362,8 @@ __all__ = [
"ExecutionFlowsResponse",
"ExternalSystemEntry",
"ExternalSystemsResponse",
+ "FileHealthTrendResponse",
+ "FileTrendPointResponse",
"FixHistoryFileResponse",
"FixHistoryResponse",
"GitMetadataResponse",
@@ -319,10 +373,21 @@ __all__ = [
"GraphExportResponse",
"GraphMetricsResponse",
"GraphNodeResponse",
+ "HealthBadgeResponse",
+ "HealthFileDelta",
+ "HealthFindingResponse",
+ "HealthFindingWithSymbolResponse",
"HealthResponse",
+ "HealthTrendAlert",
+ "HealthTrendKpiRow",
+ "HealthTrendResponse",
+ "HealthTrendSummary",
+ "HealthWorkItem",
+ "HealthWorkQueueResponse",
"HotFilesGraphResponse",
"HotFilesNodeResponse",
"HotspotResponse",
+ "JobAcceptedResponse",
"JobResponse",
"KnowledgeMapOwner",
"KnowledgeMapResponse",
@@ -339,6 +404,7 @@ __all__ = [
"ModuleNodeResponse",
"NeighboringCommunity",
"NodeSearchResult",
+ "OkResponse",
"OwnerAgentCollab",
"OwnerCoAuthor",
"OwnerFileEntry",
@@ -350,7 +416,16 @@ __all__ = [
"PageSummaryResponse",
"PageVersionResponse",
"Paginated",
+ "ProviderEntry",
+ "ProviderStatusResponse",
+ "ProviderValidationResponse",
+ "RefactoringOpportunitiesResponse",
+ "RefactoringOpportunityDetailResponse",
+ "RefactoringOpportunityStatusResponse",
+ "RefactoringPlanStatusResponse",
+ "RefactoringRollupResponse",
"RepoCreate",
+ "RepoDeletedResponse",
"RepoResponse",
"RepoStatsResponse",
"RepoSummaryRow",
diff --git a/packages/server/src/repowise/server/schemas/chat.py b/packages/server/src/repowise/server/schemas/chat.py
index 25017b47b..c68ab4cb9 100644
--- a/packages/server/src/repowise/server/schemas/chat.py
+++ b/packages/server/src/repowise/server/schemas/chat.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import json
from datetime import datetime
-from typing import Literal
+from typing import Any, Literal
from pydantic import BaseModel, Field
@@ -121,3 +121,30 @@ class ChatMessageResponse(BaseModel):
content=content,
created_at=obj.created_at, # type: ignore[attr-defined]
)
+
+
+class ChatArtifactEnvelope(BaseModel):
+ """One completed tool call, as stored inside a chat message.
+
+ ``data`` and ``evidence`` stay open: ``data`` is the raw result of
+ whichever MCP tool ran (a different shape per tool) and ``evidence`` is
+ derived from it, so closing either would turn tool variance into a 500.
+ """
+
+ id: str
+ version: int = 1
+ type: str
+ tool_name: str
+ title: str
+ presentation: str
+ data: dict[str, Any] = {}
+ evidence: dict[str, Any] = {}
+ pinned: bool = False
+ #: Absent on rows written before the envelope carried one; the legacy
+ #: normalizer backfills every other key but not this.
+ created_at: str | None = None
+
+
+class ConversationDetailResponse(BaseModel):
+ conversation: ConversationResponse
+ messages: list[ChatMessageResponse] = []
diff --git a/packages/server/src/repowise/server/schemas/claude_md.py b/packages/server/src/repowise/server/schemas/claude_md.py
new file mode 100644
index 000000000..a88b4b89c
--- /dev/null
+++ b/packages/server/src/repowise/server/schemas/claude_md.py
@@ -0,0 +1,23 @@
+"""CLAUDE.md preview and write response models."""
+
+from __future__ import annotations
+
+from pydantic import BaseModel
+
+
+class ClaudeMdResponse(BaseModel):
+ """The Repowise-managed section, rendered but not written to disk."""
+
+ content: str
+ generated_at: str
+ repo_name: str
+ #: The H3 headings present in ``content``.
+ sections: list[str] = []
+
+
+class ClaudeMdGenerateResponse(BaseModel):
+ """Where the regenerated section landed."""
+
+ status: str = "generated"
+ path: str
+ generated_at: str
diff --git a/packages/server/src/repowise/server/schemas/code_health.py b/packages/server/src/repowise/server/schemas/code_health.py
new file mode 100644
index 000000000..c2982c1d0
--- /dev/null
+++ b/packages/server/src/repowise/server/schemas/code_health.py
@@ -0,0 +1,175 @@
+"""Code-health wire models: findings, trends, churn, badge and the work queue.
+
+These mirror the dicts ``routers/code_health/serializers.py`` builds. Where a
+serializer emits ``None`` it means "no signal", never zero, so those fields are
+nullable; where it coerces to a number they are not.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from pydantic import BaseModel
+
+
+class HealthFindingResponse(BaseModel):
+ """One biomarker finding, as the table and drawer read it."""
+
+ id: str
+ file_path: str
+ biomarker_type: str
+ severity: str
+ function_name: str | None = None
+ line_start: int | None = None
+ line_end: int | None = None
+ health_impact: float
+ reason: str | None = None
+ #: Open by design: the payload differs per biomarker.
+ details: dict[str, Any] = {}
+ status: str
+ #: defect | maintainability | performance. Rows predating the split read
+ #: as ``defect``.
+ dimension: str = "defect"
+
+
+class HealthFindingWithSymbolResponse(HealthFindingResponse):
+ """A listed finding, resolved to the symbol a tool can look up.
+
+ ``None`` when the finding is file-level, or no symbol matched its span,
+ so the UI degrades to the file page.
+ """
+
+ symbol_id: str | None = None
+
+
+class ChurnComplexityPoint(BaseModel):
+ """One file on the churn-vs-complexity scatter.
+
+ Every figure is coerced by the producer, so none is nullable here: a zero
+ means zero, not "no signal".
+ """
+
+ file_path: str
+ commit_count_90d: int
+ max_ccn: int
+ nloc: int
+ score: float
+ churn_percentile: float
+
+
+class ChurnComplexityResponse(BaseModel):
+ points: list[ChurnComplexityPoint] = []
+ #: Points before the request's limit, so a slice is not read as the whole.
+ total: int = 0
+
+
+class FileTrendPointResponse(BaseModel):
+ taken_at: str | None = None
+ score: float
+ #: ``score`` with the floor undone; equal to it unless the file was on it.
+ unclamped_score: float
+
+
+class FileHealthTrendResponse(BaseModel):
+ """One file's score over time. ``points`` is empty on thin history."""
+
+ file_path: str
+ points: list[FileTrendPointResponse] = []
+ current: float | None = None
+ previous: float | None = None
+ delta: float | None = None
+ unclamped_delta: float | None = None
+ declining: bool = False
+ snapshot_count: int = 0
+
+
+class HealthTrendKpiRow(BaseModel):
+ """One snapshot in the repo-level history, newest first."""
+
+ taken_at: str | None = None
+ hotspot_health: float
+ average_health: float
+ worst_performer_path: str | None = None
+ worst_performer_score: float | None = None
+
+
+class HealthTrendSummary(BaseModel):
+ current_hotspot_health: float
+ current_average_health: float
+ previous_hotspot_health: float | None = None
+ previous_average_health: float | None = None
+ hotspot_delta: float | None = None
+ average_delta: float | None = None
+
+
+class HealthTrendAlert(BaseModel):
+ kind: str
+ metric: str
+ current: float
+ baseline: float | None = None
+ delta: float
+ message: str
+
+
+class HealthFileDelta(BaseModel):
+ """One file's movement between the last two snapshots."""
+
+ file_path: str
+ before: float
+ after: float
+ delta: float
+
+
+class HealthTrendResponse(BaseModel):
+ history: list[HealthTrendKpiRow] = []
+ summary: HealthTrendSummary
+ alerts: list[HealthTrendAlert] = []
+ #: Largest movement first, in either direction.
+ file_deltas: list[HealthFileDelta] = []
+ #: The count behind the slice, so the UI can say "N of M".
+ file_deltas_total: int = 0
+ snapshot_count: int = 0
+
+
+class HealthBadgeResponse(BaseModel):
+ """Shields-compatible badge fields for the JSON endpoint.
+
+ ``schemaVersion`` is camelCase because the Shields endpoint protocol
+ requires that exact key; without it every embedded badge renders as
+ "invalid response" instead of the score.
+ """
+
+ schemaVersion: int = 1 # noqa: N815
+ label: str
+ message: str
+ color: str
+ band: str
+
+
+class HealthWorkItem(BaseModel):
+ """One file in the triage queue, ranked by impact over effort."""
+
+ file_path: str
+ score: float
+ nloc: int
+ module: str | None = None
+ primary_biomarker: str
+ primary_severity: str
+ primary_reason: str | None = None
+ primary_function: str | None = None
+ primary_line_start: int | None = None
+ primary_line_end: int | None = None
+ primary_suggestion: str | None = None
+ primary_finding_id: str
+ #: Pre-clamp deduction magnitude over the findings that passed the filters.
+ total_impact: float
+ finding_count: int
+ biomarkers: list[str] = []
+ #: S | M | L | XL
+ effort_bucket: str
+ impact_per_effort: float
+
+
+class HealthWorkQueueResponse(BaseModel):
+ targets: list[HealthWorkItem] = []
+ total: int = 0
diff --git a/packages/server/src/repowise/server/schemas/code_quality.py b/packages/server/src/repowise/server/schemas/code_quality.py
index f38e084c7..5cfb74d93 100644
--- a/packages/server/src/repowise/server/schemas/code_quality.py
+++ b/packages/server/src/repowise/server/schemas/code_quality.py
@@ -121,3 +121,11 @@ class RepoStatsResponse(BaseModel):
doc_coverage_pct: float
freshness_score: float
dead_export_count: int
+
+
+class DeadCodeAnalyzeResponse(BaseModel):
+ """202 launch payload for a re-analysis (an index-only job, no LLM work)."""
+
+ job_id: str
+ status: str = "accepted"
+ repository_id: str
diff --git a/packages/server/src/repowise/server/schemas/decisions.py b/packages/server/src/repowise/server/schemas/decisions.py
index d61ca91ca..30316d8e1 100644
--- a/packages/server/src/repowise/server/schemas/decisions.py
+++ b/packages/server/src/repowise/server/schemas/decisions.py
@@ -226,3 +226,24 @@ class DecisionGraphResponse(BaseModel):
nodes: list[DecisionGraphNode]
decision_edges: list[DecisionGraphEdge]
code_edges: list[DecisionCodeEdge]
+
+
+class DecisionHealthResponse(BaseModel):
+ """Governance rollup: what is stale, awaiting review, and ungoverned."""
+
+ #: Record counts by status, plus ``stale``, ``unscoped`` and ``conflicts``.
+ summary: dict[str, int] = {}
+ stale_decisions: list[DecisionRecordResponse] = []
+ proposed_awaiting_review: list[DecisionRecordResponse] = []
+ #: Hotspot paths no active decision names, worst-ranked first.
+ ungoverned_hotspots: list[str] = []
+
+
+class DecisionEvidenceListResponse(BaseModel):
+ evidence: list[DecisionEvidenceResponse] = []
+
+
+class DecisionLineageResponse(BaseModel):
+ """The supersedes/refines chain, root first."""
+
+ lineage: list[DecisionLineageEntry] = []
diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.py
index 34e48fd64..384951234 100644
--- a/packages/server/src/repowise/server/schemas/git.py
+++ b/packages/server/src/repowise/server/schemas/git.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import json
from datetime import datetime
+from typing import Any
from pydantic import BaseModel
@@ -383,3 +384,17 @@ class CommitStatsResponse(BaseModel):
risk_histogram: list[RiskHistogramBucket] = []
moderate_cut: float | None = None # raw score at the low/moderate boundary
high_cut: float | None = None # raw score at the moderate/high boundary
+
+
+class CoChangeResponse(BaseModel):
+ """Files that historically change together with one file.
+
+ Partners are the verbatim persisted records, not a projection: the
+ indexer writes fields this layer does not model, and a closed row model
+ would drop them.
+ """
+
+ file_path: str
+ co_change_partners: list[dict[str, Any]] = []
+ #: Partners meeting ``min_count`` shared commits.
+ total: int = 0
diff --git a/packages/server/src/repowise/server/schemas/graph.py b/packages/server/src/repowise/server/schemas/graph.py
index 61bc07147..86112d105 100644
--- a/packages/server/src/repowise/server/schemas/graph.py
+++ b/packages/server/src/repowise/server/schemas/graph.py
@@ -3,6 +3,8 @@ dead-code graph, hot-files graph and the community super-node graph)."""
from __future__ import annotations
+from typing import Any
+
from pydantic import BaseModel
from .git import GitMetadataResponse
@@ -156,3 +158,17 @@ class ModuleEdgeResponse(BaseModel):
class ModuleGraphResponse(BaseModel):
nodes: list[ModuleNodeResponse]
edges: list[ModuleEdgeResponse]
+
+
+class DependencyPathResponse(BaseModel):
+ """The shortest dependency path between two nodes.
+
+ ``distance`` is ``-1`` and ``path`` empty when none exists; only then is
+ ``visual_context`` present, carrying the nearest common ancestors and
+ bridge suggestions the UI falls back to.
+ """
+
+ path: list[str] = []
+ distance: int
+ explanation: str
+ visual_context: dict[str, Any] | None = None
diff --git a/packages/server/src/repowise/server/schemas/refactoring.py b/packages/server/src/repowise/server/schemas/refactoring.py
new file mode 100644
index 000000000..6fe952d21
--- /dev/null
+++ b/packages/server/src/repowise/server/schemas/refactoring.py
@@ -0,0 +1,85 @@
+"""Refactoring response models.
+
+The composed opportunity and the stored rollup are assembled elsewhere — the
+opportunity in ``core.analysis.health.refactoring``, the rollup as persisted
+JSON — so those payloads stay open here. Closing them would silently drop
+whichever keys this module had not been told about, which is the failure these
+schemas exist to prevent. The envelopes around them are pinned.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from pydantic import BaseModel, ConfigDict
+
+
+class RefactoringOpportunitiesResponse(BaseModel):
+ """One page of composed opportunities, with facets and the rollup."""
+
+ #: Composed in core; see the module docstring.
+ items: list[dict[str, Any]] = []
+ total: int = 0
+ offset: int = 0
+ has_more: bool = False
+ #: ``None`` on the last page.
+ next_offset: int | None = None
+ #: Counts per facet value, scoped to the status being listed.
+ facets: dict[str, dict[str, int]] = {}
+ summary: dict[str, Any] | None = None
+ #: Present only when the request carried arguments the query ignored.
+ ignored_arguments: dict[str, str] | None = None
+
+
+class RefactoringRollupResponse(BaseModel):
+ """The repository rollup and its one lead."""
+
+ summary: dict[str, Any] = {}
+ directive: dict[str, Any] = {}
+
+
+class RefactoringOpportunityStatusResponse(BaseModel):
+ """What one opportunity-level triage decision wrote."""
+
+ opportunity_id: str
+ status: str
+ #: Member plans the transition reached; the route 409s when it is zero.
+ steps_updated: int
+ status_changed_at: str | None = None
+
+
+class RefactoringPlanStatusResponse(BaseModel):
+ """What one plan-level triage decision wrote."""
+
+ id: str
+ public_id: str | None = None
+ status: str
+ status_reason: str | None = None
+ status_changed_at: str | None = None
+
+
+class RefactoringOpportunityDetailResponse(BaseModel):
+ """One opportunity: its ordered steps, evidence, validation and plans.
+
+ ``extra="allow"``: the base row is composed in core and this response
+ spreads an evidence block over it, so the declared keys are the stable
+ part and anything else passes through rather than being dropped.
+ """
+
+ model_config = ConfigDict(extra="allow")
+
+ resolved: bool
+ steps: list[dict[str, Any]] = []
+ steps_total: int = 0
+ steps_emitted: int = 0
+ #: Present only when the page stopped short of the full step list.
+ steps_reduced_reason: str | None = None
+ steps_next_cursor: int | None = None
+ validation_profiles: list[dict[str, Any]] = []
+ affected_files: list[str] = []
+ lead_finding_ids: list[str] = []
+ next_actions: list[dict[str, Any]] = []
+ #: Present when steps were returned and plans were requested.
+ plans: list[dict[str, Any]] | None = None
+ #: Present when a step names a symbol an earlier step moves.
+ ordering_note: str | None = None
diff --git a/packages/server/src/repowise/server/schemas/repository.py b/packages/server/src/repowise/server/schemas/repository.py
index 3f816da8a..846416d78 100644
--- a/packages/server/src/repowise/server/schemas/repository.py
+++ b/packages/server/src/repowise/server/schemas/repository.py
@@ -89,6 +89,26 @@ class RepoResponse(BaseModel):
)
+class RepoDeletedResponse(BaseModel):
+ """What a repository delete removed, for the confirmation toast."""
+
+ ok: bool = True
+ deleted_pages: int = 0
+
+
+class JobAcceptedResponse(BaseModel):
+ """The 202 payload every background-job launch returns.
+
+ ``stream_token`` authorizes ``/api/jobs/{job_id}/stream`` directly, so a
+ client can attach without a second round-trip or an API key in the query
+ string.
+ """
+
+ job_id: str
+ status: str = "accepted"
+ stream_token: str
+
+
class RepoSummaryRow(BaseModel):
"""One repository's headline figures, for the multi-repo dashboard.
diff --git a/packages/server/src/repowise/server/schemas/ui_helpers.py b/packages/server/src/repowise/server/schemas/ui_helpers.py
index 3fca87bad..69b0500de 100644
--- a/packages/server/src/repowise/server/schemas/ui_helpers.py
+++ b/packages/server/src/repowise/server/schemas/ui_helpers.py
@@ -10,6 +10,12 @@ class WebhookResponse(BaseModel):
status: str = "accepted"
+class OkResponse(BaseModel):
+ """Acknowledgement for a mutation with nothing else to report."""
+
+ ok: bool = True
+
+
class SetActiveProviderRequest(BaseModel):
provider: str
model: str | None = None
@@ -25,6 +31,44 @@ class SetApiKeyRequest(BaseModel):
repo_id: str | None = None
+class ProviderEntry(BaseModel):
+ """One provider in the catalog, as the settings picker renders it."""
+
+ id: str
+ name: str
+ #: Catalog models, plus the active model when it is configured but
+ #: uncataloged (a local LiteLLM alias), so the picker can display it.
+ models: list[str] = []
+ default_model: str | None = None
+ #: Has a key, or needs none.
+ configured: bool = False
+
+
+class ActiveProviderSelection(BaseModel):
+ """The provider/model this scope resolves to; ``None`` when unset."""
+
+ provider: str | None = None
+ model: str | None = None
+
+
+class ProviderStatusResponse(BaseModel):
+ active: ActiveProviderSelection
+ providers: list[ProviderEntry] = []
+
+
+class ProviderValidationResponse(BaseModel):
+ """Outcome of the live single-provider smoke test.
+
+ A failed probe reports ``ok=False`` with ``error`` set rather than raising,
+ so the settings UI renders a clean error state.
+ """
+
+ ok: bool
+ provider: str | None = None
+ model: str | None = None
+ error: str | None = None
+
+
class CostGroupResponse(BaseModel):
group: str
calls: int
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index f93ca3db6..68cd3eee4 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -330,6 +330,9 @@ class WorkspaceBreakingChange(BaseModel):
provider_repo: str
provider_file: str
provider_symbol: str
+ #: Looked-up id for the changed provider symbol; ``None`` when the
+ #: contract did not resolve to one.
+ provider_symbol_id: str | None = None
provider_service: str | None = None
provider_node_id: str = ""
detail: str
diff --git a/packages/server/src/repowise/server/services/external_system_relationships.py b/packages/server/src/repowise/server/services/external_system_relationships.py
index 704f19b49..0c17bbbe7 100644
--- a/packages/server/src/repowise/server/services/external_system_relationships.py
+++ b/packages/server/src/repowise/server/services/external_system_relationships.py
@@ -21,6 +21,7 @@ from repowise.core.analysis.external_systems import (
DEFAULT_RELATIONSHIP_EDGE_LIMIT,
DEFAULT_RELATIONSHIP_NODE_LIMIT,
EVIDENCE_TARGET_LIMIT,
+ IMPORT_EDGE_TYPE,
Scope,
build_importing_files,
build_relationship_graph,
@@ -107,7 +108,7 @@ async def _import_edges(session: AsyncSession, repository_id: str, target_nodes:
)
.where(
GraphEdge.repository_id == repository_id,
- GraphEdge.edge_type == "imports",
+ GraphEdge.edge_type == IMPORT_EDGE_TYPE,
GraphEdge.target_node_id.in_(target_nodes),
)
)
diff --git a/packages/server/src/repowise/server/services/external_systems.py b/packages/server/src/repowise/server/services/external_systems.py
index 721e960f1..72e56f62a 100644
--- a/packages/server/src/repowise/server/services/external_systems.py
+++ b/packages/server/src/repowise/server/services/external_systems.py
@@ -17,6 +17,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.external_systems import (
DEFAULT_SUMMARY_LIMIT,
+ IMPORT_EDGE_TYPE,
Scope,
build_package_summary,
)
@@ -78,7 +79,7 @@ def _import_edge_query(repository_id: str):
)
.where(
GraphEdge.repository_id == repository_id,
- GraphEdge.edge_type == "imports",
+ GraphEdge.edge_type == IMPORT_EDGE_TYPE,
)
)
diff --git a/packages/types/package.json b/packages/types/package.json
index a63f13607..54e0f0dfc 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -32,7 +32,8 @@
"./health": "./src/health.ts",
"./coupling": "./src/coupling.ts",
"./stats": "./src/stats.ts",
- "./refactoring": "./src/refactoring.ts"
+ "./refactoring": "./src/refactoring.ts",
+ "./generated/http": "./src/generated/http.ts"
},
"publishConfig": {
"registry": "https://npm.pkg.github.com",
diff --git a/packages/types/src/chat.ts b/packages/types/src/chat.ts
index 90d161257..f3a32f430 100644
--- a/packages/types/src/chat.ts
+++ b/packages/types/src/chat.ts
@@ -284,6 +284,11 @@ export interface ChangeHealthDeltaData {
| "rules_mismatch"
| "stale_baseline";
explanation: string;
+ /**
+ * How the two sides were compared, e.g. `both_sides_analyzed` /
+ * `not_compared`. Open on the wire: the producer types it as a plain string.
+ */
+ basis: string;
introduced: number;
worsened: number;
resolved: number;
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
new file mode 100644
index 000000000..be1c432da
--- /dev/null
+++ b/packages/types/src/generated/http.ts
@@ -0,0 +1,2902 @@
+// Generated from the FastAPI application's OpenAPI schema. Do not edit.
+//
+// Regenerate with: python scripts/generate_http_types.py
+// CI fails when this file and the live schema disagree.
+//
+// Scope: the HTTP boundary only. Artifact, UI and other non-wire domain types
+// stay hand-written in the sibling modules.
+//
+// `?` mirrors the schema's `required` list, which states what a request may
+// omit. A response field with a server-side default is still always sent.
+
+/** The provider/model this scope resolves to; ``None`` when unset. */
+export interface ActiveProviderSelection {
+ provider?: string | null;
+ model?: string | null;
+}
+
+/** One month of agent-vs-human commit volume. */
+export interface AgentTrendBucket {
+ month: string;
+ total_commits: number;
+ agent_commits: number;
+ agent_pct: number;
+ tier_counts?: Record<string, unknown>;
+}
+
+/** Monthly agent-share trend across the indexed commit window. */
+export interface AgentTrendResponse {
+ buckets: AgentTrendBucket[];
+ total_commits: number;
+ agent_commits: number;
+ agent_pct: number;
+ agent_names?: Record<string, unknown>[];
+}
+
+export interface ArchEdgeResponse {
+ source: string;
+ target: string;
+ edge_type: string;
+ direction: string;
+ weight: number;
+ confidence: number;
+}
+
+export interface ArchLayerResponse {
+ id: string;
+ name: string;
+ description: string;
+ node_ids: string[];
+ file_count: number;
+ complexity_distribution: Record<string, number>;
+ health_score: number | null;
+ sub_groups?: ArchSubGroupResponse[];
+ display_order?: number;
+}
+
+export interface ArchNodeResponse {
+ id: string;
+ node_type: string;
+ name: string;
+ file_path: string | null;
+ line_range: number[] | null;
+ summary: string;
+ complexity: string;
+ tags: string[];
+ language: string | null;
+ pagerank: number;
+ pagerank_percentile: number;
+ betweenness: number;
+ in_degree: number;
+ out_degree: number;
+ community_id: number | null;
+ is_entry_point: boolean;
+ is_test: boolean;
+ is_hotspot: boolean;
+ is_dead: boolean;
+ has_doc: boolean;
+ primary_owner: string | null;
+ primary_owner_pct: number | null;
+ bus_factor: number | null;
+}
+
+export interface ArchSubGroupResponse {
+ id: string;
+ name: string;
+ node_ids: string[];
+}
+
+export interface ArchTourStepResponse {
+ order: number;
+ title: string;
+ description: string;
+ node_ids: string[];
+ target_path?: string | null;
+ layer_id?: string | null;
+ reason?: string;
+ depth?: number | null;
+ kind?: string;
+ page_type?: string | null;
+}
+
+export interface ArchitectureEdgeResponse {
+ source: number;
+ target: number;
+ edge_count: number;
+}
+
+export interface ArchitectureGraphResponse {
+ nodes: ArchitectureNodeResponse[];
+ edges: ArchitectureEdgeResponse[];
+}
+
+export interface ArchitectureNodeResponse {
+ community_id: number;
+ label: string;
+ cohesion: number;
+ member_count: number;
+ top_file: string;
+ avg_pagerank: number;
+ hotspot_count?: number;
+ dead_count?: number;
+ has_decision?: boolean;
+ doc_coverage_pct?: number;
+ languages?: string[];
+}
+
+export interface ArchitectureViewResponse {
+ project_name: string;
+ project_description: string;
+ layers: ArchLayerResponse[];
+ nodes: ArchNodeResponse[];
+ edges: ArchEdgeResponse[];
+ tour: ArchTourStepResponse[];
+ total_files: number;
+ total_symbols: number;
+ total_edges: number;
+ languages: string[];
+ frameworks: string[];
+ external_systems: C4ExternalSystemResponse[];
+ entry_points?: string[];
+ entry_candidates?: string[];
+}
+
+export interface ArtifactUpdateRequest {
+ pinned: boolean;
+}
+
+export interface BlastRadiusRequest {
+ changed_files: string[];
+ max_depth?: number;
+}
+
+export interface BlastRadiusResponse {
+ direct_risks: DirectRiskEntry[];
+ transitive_affected: TransitiveEntry[];
+ cochange_warnings: CochangeWarning[];
+ recommended_reviewers: ReviewerEntry[];
+ test_gaps: string[];
+ test_impact: TestImpactResponse;
+ structural_impact_score: number;
+ structural_impact_band: "localized" | "moderate" | "broad";
+ structural_impact_scale: RiskScalarSemantics;
+ overall_risk_score: number;
+ overall_risk_score_compatibility: RiskCompatibilityField;
+}
+
+export interface C4ComponentResponse {
+ id: string;
+ name: string;
+ path: string;
+ container_id: string;
+ file_count: number;
+ symbol_count: number;
+}
+
+export interface C4ContainerResponse {
+ id: string;
+ name: string;
+ path: string;
+ language: string;
+ file_count: number;
+ symbol_count: number;
+ hotspot_count?: number;
+ dead_count?: number;
+}
+
+export interface C4ExternalSystemResponse {
+ id: string;
+ name: string;
+ display_name: string;
+ category: string;
+ ecosystem: string;
+ version?: string | null;
+ io_kind?: string | null;
+}
+
+export interface C4L1Response {
+ system: C4SystemResponse;
+ people: C4PersonResponse[];
+ external_systems: C4ExternalSystemResponse[];
+ relations: C4RelationResponse[];
+}
+
+export interface C4L2Response {
+ containers: C4ContainerResponse[];
+ external_systems: C4ExternalSystemResponse[];
+ relations: C4RelationResponse[];
+}
+
+export interface C4L3Response {
+ container: C4ContainerResponse;
+ components: C4ComponentResponse[];
+ external_systems: C4ExternalSystemResponse[];
+ relations: C4RelationResponse[];
+}
+
+export interface C4PersonResponse {
+ id: string;
+ name: string;
+ description?: string;
+ kind?: string;
+}
+
+export interface C4RelationResponse {
+ source_id: string;
+ target_id: string;
+ label?: string;
+ edge_count?: number;
+ edge_types?: string[];
+ coupling?: string;
+}
+
+export interface C4SystemResponse {
+ id: string;
+ name: string;
+ description?: string;
+}
+
+export interface CallerCalleeEntry {
+ symbol_id: string;
+ name: string;
+ kind: string;
+ file: string;
+ start_line?: number | null;
+ edge_type: string;
+ confidence: number;
+ resolution_origin?: string | null;
+}
+
+export interface CallersCalleesResponse {
+ symbol_id: string;
+ symbol: SymbolNodeSummary;
+ callers: CallerCalleeEntry[];
+ callees: CallerCalleeEntry[];
+ caller_count: number;
+ callee_count: number;
+ truncated: boolean;
+ relations?: SymbolRelationGroup[];
+}
+
+/** The Kamei change-shape features the risk model scores. */
+export interface ChangeFeaturesResponse {
+ la: number;
+ ld: number;
+ nf: number;
+ nd: number;
+ ns: number;
+ entropy: number;
+ exp: number | null;
+}
+
+export interface ChangelogEntryModel {
+ version: string;
+ label?: string | null;
+ sections: ChangelogSectionModel[];
+}
+
+export interface ChangelogResponse {
+ entries: ChangelogEntryModel[];
+}
+
+export interface ChangelogSectionModel {
+ name: string;
+ items: string[];
+}
+
+/**
+ * One completed tool call, as stored inside a chat message.
+ *
+ * ``data`` and ``evidence`` stay open: ``data`` is the raw result of
+ * whichever MCP tool ran (a different shape per tool) and ``evidence`` is
+ * derived from it, so closing either would turn tool variance into a 500.
+ */
+export interface ChatArtifactEnvelope {
+ id: string;
+ version?: number;
+ type: string;
+ tool_name: string;
+ title: string;
+ presentation: string;
+ data?: Record<string, unknown>;
+ evidence?: Record<string, unknown>;
+ pinned?: boolean;
+ created_at?: string | null;
+}
+
+export interface ChatMessageResponse {
+ id: string;
+ conversation_id: string;
+ role: string;
+ content: Record<string, unknown>;
+ created_at: string;
+}
+
+/** Navigation metadata supplied by a product chat surface. */
+export interface ChatPageContext {
+ kind: "repository" | "overview" | "documentation" | "architecture" | "graph" | "health" | "refactoring" | "file" | "symbol" | "module" | "dependency" | "commit" | "contributor" | "decision" | "risk" | "security" | "usage" | "settings" | "chat";
+ label: string;
+ target?: string | null;
+ target_kind?: "path" | "symbol" | "module" | "commit" | "person" | "decision" | "documentation" | null;
+}
+
+export interface ChatRequest {
+ message: string;
+ conversation_id?: string | null;
+ provider?: string | null;
+ model?: string | null;
+ context?: ChatPageContext | null;
+}
+
+/**
+ * One file on the churn-vs-complexity scatter.
+ *
+ * Every figure is coerced by the producer, so none is nullable here: a zero
+ * means zero, not "no signal".
+ */
+export interface ChurnComplexityPoint {
+ file_path: string;
+ commit_count_90d: number;
+ max_ccn: number;
+ nloc: number;
+ score: number;
+ churn_percentile: number;
+}
+
+export interface ChurnComplexityResponse {
+ points?: ChurnComplexityPoint[];
+ total?: number;
+}
+
+/** Where the regenerated section landed. */
+export interface ClaudeMdGenerateResponse {
+ status?: string;
+ path: string;
+ generated_at: string;
+}
+
+/** The Repowise-managed section, rendered but not written to disk. */
+export interface ClaudeMdResponse {
+ content: string;
+ generated_at: string;
+ repo_name: string;
+ sections?: string[];
+}
+
+/**
+ * Files that historically change together with one file.
+ *
+ * Partners are the verbatim persisted records, not a projection: the
+ * indexer writes fields this layer does not model, and a closed row model
+ * would drop them.
+ */
+export interface CoChangeResponse {
+ file_path: string;
+ co_change_partners?: Record<string, unknown>[];
+ total?: number;
+}
+
+export interface CochangeWarning {
+ changed: string;
+ missing_partner: string;
+ score: number;
+}
+
+/** A single commit with its full, attributable risk-driver breakdown. */
+export interface CommitDetailResponse {
+ sha: string;
+ short_sha: string;
+ author_name: string;
+ author_email: string;
+ committed_at: string | null;
+ subject: string;
+ lines_added: number;
+ lines_deleted: number;
+ files_changed: number;
+ dirs_changed: number;
+ subsystems_changed: number;
+ entropy: number;
+ is_fix: boolean;
+ change_risk_score: number | null;
+ change_risk_level: string | null;
+ risk_percentile: number;
+ review_priority: string;
+ top_driver?: string | null;
+ author_experience?: number | null;
+ author_commit_count?: number | null;
+ agent_name?: string | null;
+ agent_autonomy_tier?: number | null;
+ agent_confidence?: string | null;
+ drivers?: RiskDriverResponse[];
+ agent_channel?: string | null;
+}
+
+/**
+ * One time bucket of commit-category counts for the Code Evolution timeline.
+ *
+ * ``counts`` keys are drawn from
+ * :data:`repowise.core.ingestion.git_indexer._constants.EVOLUTION_CATEGORIES`;
+ * a category is omitted when its count is zero in this bucket.
+ */
+export interface CommitEvolutionBucket {
+ period: string;
+ start: string;
+ total: number;
+ counts?: Record<string, number>;
+}
+
+/**
+ * Commit-category mix over time — the repo's development "story arc".
+ *
+ * Each commit is classified into exactly one category (feature/fix/refactor/
+ * docs/test/deps/chore/other) from its subject and bucketed by ``granularity``.
+ * The UI renders ``buckets`` as a stacked area (share or volume).
+ */
+export interface CommitEvolutionResponse {
+ buckets: CommitEvolutionBucket[];
+ categories: string[];
+ totals?: Record<string, number>;
+ total_commits: number;
+ granularity: string;
+ first_commit_at?: string | null;
+ last_commit_at?: string | null;
+}
+
+/**
+ * One per-commit row from the ``git_commits`` table.
+ *
+ * Carries the stored raw change-risk plus a **repo-relative** normalization
+ * (``risk_percentile`` + ``review_priority``). The raw ``change_risk_level``
+ * is the absolute calibration band — kept for transparency but de-emphasized
+ * in the UI, because it skews high on repos with large typical commits. The
+ * review-priority queue ranks on ``risk_percentile`` instead.
+ */
+export interface CommitResponse {
+ sha: string;
+ short_sha: string;
+ author_name: string;
+ author_email: string;
+ committed_at: string | null;
+ subject: string;
+ lines_added: number;
+ lines_deleted: number;
+ files_changed: number;
+ dirs_changed: number;
+ subsystems_changed: number;
+ entropy: number;
+ is_fix: boolean;
+ change_risk_score: number | null;
+ change_risk_level: string | null;
+ risk_percentile: number;
+ review_priority: string;
+ top_driver?: string | null;
+ author_experience?: number | null;
+ author_commit_count?: number | null;
+ agent_name?: string | null;
+ agent_autonomy_tier?: number | null;
+ agent_confidence?: string | null;
+}
+
+/**
+ * Repo-wide commit aggregates for the commits-page headline stat cards.
+ *
+ * Computed over **all** indexed commits, not the loaded page — the paginated
+ * feed only returns a window, so client-side reductions over it under-count
+ * (e.g. a risk-sorted first page is all top-tercile). These are the honest
+ * totals for the whole repository.
+ */
+export interface CommitStatsResponse {
+ total_commits: number;
+ high_priority_count: number;
+ fix_commit_count: number;
+ agent_commit_count: number;
+ avg_entropy: number;
+ risk_histogram?: RiskHistogramBucket[];
+ moderate_cut?: number | null;
+ high_cut?: number | null;
+}
+
+export interface CommunityDetailResponse {
+ community_id: number;
+ label: string;
+ cohesion: number;
+ member_count: number;
+ members: CommunityMember[];
+ truncated: boolean;
+ neighboring_communities: NeighboringCommunity[];
+}
+
+export interface CommunityMember {
+ path: string;
+ pagerank: number;
+ is_entry_point: boolean;
+}
+
+export interface CommunitySliceNodeResponse {
+ node_id: string;
+ node_type: string;
+ language: string;
+ symbol_count: number;
+ pagerank: number;
+ betweenness: number;
+ community_id: number;
+ is_test?: boolean;
+ is_entry_point?: boolean;
+ has_doc?: boolean;
+ is_hotspot?: boolean;
+ churn_percentile?: number | null;
+ is_dead?: boolean;
+ dead_confidence?: number | null;
+ has_decision?: boolean;
+ primary_owner?: string | null;
+ is_boundary?: boolean;
+}
+
+export interface CommunitySliceResponse {
+ nodes: CommunitySliceNodeResponse[];
+ links: GraphEdgeResponse[];
+ community_id: number;
+ member_count: number;
+ truncated?: boolean;
+}
+
+export interface CommunitySummaryItem {
+ community_id: number;
+ label: string;
+ cohesion: number;
+ member_count: number;
+ top_file: string;
+}
+
+export interface ConversationDetailResponse {
+ conversation: ConversationResponse;
+ messages?: ChatMessageResponse[];
+}
+
+export interface ConversationForkRequest {
+ through_message_id?: string | null;
+ before_message_id?: string | null;
+}
+
+export interface ConversationResponse {
+ id: string;
+ repository_id: string;
+ title: string;
+ message_count?: number;
+ pinned?: boolean;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface ConversationUpdateRequest {
+ title?: string | null;
+ pinned?: boolean | null;
+}
+
+export interface CoordinatorHealthResponse {
+ sql_pages: number | null;
+ sql_decisions: number | null;
+ vector_count: number | null;
+ vector_page_count: number | null;
+ vector_decision_count: number | null;
+ graph_nodes: number | null;
+ drift_pct: number | null;
+ page_drift_pct: number | null;
+ decision_drift_pct: number | null;
+ status: string;
+ detail?: string | null;
+}
+
+export interface CostGroupResponse {
+ group: string;
+ calls: number;
+ input_tokens: number;
+ output_tokens: number;
+ cost_usd: number;
+}
+
+export interface CostSummaryResponse {
+ total_cost_usd: number;
+ total_calls: number;
+ total_input_tokens: number;
+ total_output_tokens: number;
+ since: string | null;
+}
+
+export interface CouplingEdgeResponse {
+ source: string;
+ target: string;
+ strength: number;
+ last_co_change?: string | null;
+ support?: number;
+ confidence_ab?: number | null;
+ confidence_ba?: number | null;
+ structural?: "corroborated" | "unexplained" | "not_applicable" | null;
+ dependency_kind?: string | null;
+}
+
+export interface CouplingGraphResponse {
+ nodes?: CouplingNodeResponse[];
+ edges?: CouplingEdgeResponse[];
+ total_edges?: number;
+ coupled_files?: number;
+ total_files?: number;
+}
+
+export interface CouplingNodeResponse {
+ file_path: string;
+ module?: string | null;
+ score?: number | null;
+ nloc?: number;
+}
+
+/** 202 launch payload for a re-analysis (an index-only job, no LLM work). */
+export interface DeadCodeAnalyzeResponse {
+ job_id: string;
+ status?: string;
+ repository_id: string;
+}
+
+export interface DeadCodeFindingResponse {
+ id: string;
+ kind: string;
+ file_path: string;
+ symbol_name: string | null;
+ symbol_kind: string | null;
+ confidence: number;
+ reason: string;
+ lines: number;
+ start_line: number | null;
+ end_line: number | null;
+ safe_to_delete: boolean;
+ risk_factors: string[];
+ evidence: string[];
+ primary_owner: string | null;
+ status: string;
+ note: string | null;
+ last_commit_at: string | null;
+ commit_count_90d: number;
+}
+
+export interface DeadCodeGraphNodeResponse {
+ node_id: string;
+ node_type: string;
+ language: string;
+ symbol_count: number;
+ pagerank: number;
+ betweenness: number;
+ community_id: number;
+ is_test?: boolean;
+ is_entry_point?: boolean;
+ has_doc?: boolean;
+ is_hotspot?: boolean;
+ churn_percentile?: number | null;
+ is_dead?: boolean;
+ dead_confidence?: number | null;
+ has_decision?: boolean;
+ primary_owner?: string | null;
+ confidence_group: string;
+}
+
+export interface DeadCodeGraphResponse {
+ nodes: DeadCodeGraphNodeResponse[];
+ links: GraphEdgeResponse[];
+}
+
+export interface DeadCodePatchRequest {
+ status: string;
+ note?: string | null;
+}
+
+export interface DeadCodeSummaryResponse {
+ total_findings: number;
+ confidence_summary: Record<string, unknown>;
+ deletable_lines: number;
+ total_lines: number;
+ by_kind: Record<string, unknown>;
+}
+
+/** A link from a decision to a governed file or module. */
+export interface DecisionCodeEdge {
+ decision_id: string;
+ node_id: string;
+ link_type: string;
+}
+
+/**
+ * Counts by status for a repository, from a grouped COUNT.
+ *
+ * Exists so a caller can state a total it actually measured. The list
+ * endpoint caps at 500 rows, so counting the page reported "97 of 100" on a
+ * repository holding several hundred records.
+ */
+export interface DecisionCountsResponse {
+ total: number;
+ active: number;
+ proposed: number;
+ superseded: number;
+ deprecated: number;
+}
+
+export interface DecisionCreate {
+ title: string;
+ context?: string;
+ decision?: string;
+ rationale?: string;
+ alternatives?: string[];
+ consequences?: string[];
+ affected_files?: string[];
+ affected_modules?: string[];
+ tags?: string[];
+}
+
+export interface DecisionEvidenceListResponse {
+ evidence?: DecisionEvidenceResponse[];
+}
+
+/** One provenance row supporting a decision record. */
+export interface DecisionEvidenceResponse {
+ id: string;
+ source: string;
+ source_rank: number;
+ evidence_file: string | null;
+ evidence_line: number | null;
+ evidence_commit: string | null;
+ source_quote: string;
+ confidence: number;
+ verification: string;
+ created_at: string;
+}
+
+/** A typed directed edge between two decision records. */
+export interface DecisionGraphEdge {
+ src: string;
+ dst: string;
+ kind: string;
+ confidence: number;
+ evidence: string;
+}
+
+/** A decision record represented as a graph node. */
+export interface DecisionGraphNode {
+ id: string;
+ title: string;
+ status: string;
+ source: string;
+ confidence: number;
+ staleness_score: number;
+ verification: string;
+}
+
+/** Full decision graph: nodes, decision→decision edges, decision→code edges. */
+export interface DecisionGraphResponse {
+ nodes: DecisionGraphNode[];
+ decision_edges: DecisionGraphEdge[];
+ code_edges: DecisionCodeEdge[];
+}
+
+/** Governance rollup: what is stale, awaiting review, and ungoverned. */
+export interface DecisionHealthResponse {
+ summary?: Record<string, number>;
+ stale_decisions?: DecisionRecordResponse[];
+ proposed_awaiting_review?: DecisionRecordResponse[];
+ ungoverned_hotspots?: string[];
+}
+
+/** One node in a decision lineage chain (root → … → current). */
+export interface DecisionLineageEntry {
+ id: string;
+ title: string;
+ status: string;
+ source: string;
+ relation: string | null;
+}
+
+/** The supersedes/refines chain, root first. */
+export interface DecisionLineageResponse {
+ lineage?: DecisionLineageEntry[];
+}
+
+export interface DecisionRecordResponse {
+ id: string;
+ repository_id: string;
+ title: string;
+ status: string;
+ context: string;
+ decision: string;
+ rationale: string;
+ alternatives: string[];
+ consequences: string[];
+ affected_files: string[];
+ affected_modules: string[];
+ tags: string[];
+ source: string;
+ evidence_commits: string[];
+ evidence_file: string | null;
+ evidence_line: number | null;
+ confidence: number;
+ staleness_score: number;
+ verification?: string;
+ scope?: string | null;
+ superseded_by: string | null;
+ last_code_change: string | null;
+ created_at: string;
+ updated_at: string;
+ evidence_count?: number | null;
+ evidence_preview?: EvidencePreview | null;
+}
+
+/**
+ * PATCH body for /decisions/{id}.
+ *
+ * All fields are optional — clients can update status alone (the historical
+ * contract), the linked modules / files alone (governance editor), or both
+ * in a single request. Fields left at ``None`` are preserved.
+ */
+export interface DecisionStatusUpdate {
+ status?: string | null;
+ superseded_by?: string | null;
+ affected_modules?: string[] | null;
+ affected_files?: string[] | null;
+}
+
+/**
+ * The shortest dependency path between two nodes.
+ *
+ * ``distance`` is ``-1`` and ``path`` empty when none exists; only then is
+ * ``visual_context`` present, carrying the nearest common ancestors and
+ * bridge suggestions the UI falls back to.
+ */
+export interface DependencyPathResponse {
+ path?: string[];
+ distance: number;
+ explanation: string;
+ visual_context?: Record<string, unknown> | null;
+}
+
+export interface DirectRiskEntry {
+ path: string;
+ structural_score: number;
+ risk_score: number;
+ temporal_hotspot: number;
+ centrality: number;
+}
+
+export interface DistillSavingsGroup {
+ group: string;
+ events: number;
+ raw_tokens: number;
+ distilled_tokens: number;
+ saved_tokens: number;
+}
+
+/**
+ * Savings rollup for the Costs page hero card.
+ *
+ * The ``distill`` block (``saved_tokens`` etc.) covers the ``repowise
+ * distill`` command/hook path. The ``mcp`` block surfaces tokens already
+ * dropped past MCP response budgets (the ``omissions`` store), which the
+ * distill ledger never recorded. Savings are priced at the *coding agent's*
+ * detected model (``pricing_model`` / ``pricing_agent`` / ``pricing_source``)
+ * — they are input tokens that agent never had to read. ``available`` is
+ * False when the repo has no omission store on disk (feature unused).
+ */
+export interface DistillSavingsResponse {
+ available: boolean;
+ events?: number;
+ raw_tokens?: number;
+ distilled_tokens?: number;
+ saved_tokens?: number;
+ estimated_usd_saved?: number;
+ pricing_model?: string;
+ pricing_agent?: string;
+ pricing_source?: string;
+ per_filter?: DistillSavingsGroup[];
+ per_day?: DistillSavingsGroup[];
+ mcp_events?: number;
+ mcp_tokens?: number;
+ mcp_queries?: number;
+ mcp_per_tool?: McpDropGroup[];
+ missed_events?: number;
+ missed_tokens_est?: number;
+ missed_window_days?: number;
+ reread_events?: number;
+ reread_tokens_est?: number;
+}
+
+export interface EgoGraphResponse {
+ nodes: GraphNodeResponse[];
+ links: GraphEdgeResponse[];
+ center_node_id: string;
+ center_git_meta: GitMetadataResponse | null;
+ inbound_count: number;
+ outbound_count: number;
+}
+
+/**
+ * Counts by tier and by kind, from a grouped read of the same filters.
+ *
+ * Exists for the same reason the decision counts endpoint does: a page that
+ * counts its own rows reports the size of a window, not the size of a store.
+ */
+export interface EpisodeCountsResponse {
+ available?: boolean;
+ total?: number;
+ by_tier?: Record<string, number>;
+ by_kind?: Record<string, number>;
+}
+
+/**
+ * One episode, whole, with the currency question actually asked.
+ *
+ * ``current`` is the gate half of the verdict and ``still_true`` the sentence
+ * half. Both are served because they answer different questions: a reader
+ * asking *what happened here* wants the sentence even when the scope has
+ * moved, while anything putting a claim beside a statement about the present
+ * must respect the boolean.
+ */
+export interface EpisodeDetail {
+ id: string;
+ tier: string;
+ kind: string;
+ subject: string;
+ body: string;
+ evidence: string;
+ nodes: string[];
+ node_count: number;
+ birth_commit: string | null;
+ birth_at: string | null;
+ last_seen_at: string | null;
+ still_true: string;
+ current: boolean;
+}
+
+/** A page of summaries, with the measured total behind it. */
+export interface EpisodeListResponse {
+ available?: boolean;
+ total?: number;
+ episodes?: EpisodeSummary[];
+}
+
+/** One timeline row. No body, and no git call was made to build it. */
+export interface EpisodeSummary {
+ id: string;
+ tier: string;
+ kind: string;
+ subject: string;
+ evidence: string;
+ nodes: string[];
+ node_count: number;
+ birth_commit: string | null;
+ birth_at: string | null;
+ last_seen_at: string | null;
+ still_true?: string | null;
+}
+
+/** The top-ranked evidence row, slimmed for list rows. */
+export interface EvidencePreview {
+ source: string;
+ source_quote: string;
+ verification: string;
+ evidence_file?: string | null;
+ evidence_line?: number | null;
+}
+
+export interface ExecutionFlowEntry {
+ entry_point: string;
+ entry_point_name: string;
+ entry_point_score: number;
+ trace: string[];
+ depth: number;
+ crosses_community: boolean;
+ communities_visited: number[];
+ termination?: string | null;
+ termination_detail?: Record<string, number> | null;
+ trace_via?: (string | null)[] | null;
+}
+
+export interface ExecutionFlowsResponse {
+ total_entry_points: number;
+ flows: ExecutionFlowEntry[];
+}
+
+/** One declared third-party dependency. */
+export interface ExternalSystemEntry {
+ name: string;
+ display_name: string;
+ ecosystem: string;
+ category: string;
+ io_kind?: string | null;
+ version?: string | null;
+ declared_in: string;
+ is_dev_dep?: boolean;
+}
+
+/** One persisted external graph node linked to the selected package. */
+export interface ExternalSystemGraphTarget {
+ node_id: string;
+ match_basis: "exact" | "subpath" | "mapped";
+}
+
+export interface ExternalSystemImportingFile {
+ path: string;
+ language: string;
+ import_edge_count: number;
+ matched_external_node_count: number;
+}
+
+/** One independently bounded page of files behind an aggregate node. */
+export interface ExternalSystemImportingFilesResponse {
+ package_key: string;
+ aggregate_key: string;
+ items: ExternalSystemImportingFile[];
+ total: number;
+ returned: number;
+ limit: number;
+ offset: number;
+ truncated: boolean;
+ scope: "primary" | "all";
+}
+
+export interface ExternalSystemRelationshipEdge {
+ source: string;
+ target: string;
+ import_edge_count: number;
+}
+
+/** Bounded aggregate-first relationship graph for one declared package. */
+export interface ExternalSystemRelationshipGraphResponse {
+ package_key: string;
+ package_name: string;
+ package_node_id: string;
+ match_basis: "exact" | "subpath" | "mapped" | "mixed" | "unresolved";
+ matched_external_nodes: ExternalSystemGraphTarget[];
+ matched_external_nodes_total: number;
+ matched_external_nodes_truncated: boolean;
+ evidence_target_limit: number;
+ evidence_truncated: boolean;
+ nodes: ExternalSystemRelationshipNode[];
+ edges: ExternalSystemRelationshipEdge[];
+ aggregate_total: number;
+ aggregate_returned: number;
+ edge_total: number;
+ edge_returned: number;
+ importing_file_total: number;
+ import_edge_total: number;
+ node_limit: number;
+ edge_limit: number;
+ truncated: boolean;
+ scope: "primary" | "all";
+}
+
+/** A first-party graph community that imports the selected package. */
+export interface ExternalSystemRelationshipNode {
+ aggregate_key: string;
+ label: string;
+ community_id: number;
+ importing_file_count: number;
+ import_edge_count: number;
+ top_file?: string | null;
+}
+
+/** One canonical package with declaration and graph-usage aggregates. */
+export interface ExternalSystemSummaryEntry {
+ package_key: string;
+ name: string;
+ display_name: string;
+ ecosystem: string;
+ category: string;
+ io_kind?: string | null;
+ runtime_declared: boolean;
+ dev_declared: boolean;
+ declaration_count: number;
+ manifest_count: number;
+ versions: string[];
+ versions_total: number;
+ versions_truncated: boolean;
+ multiple_versions: boolean;
+ external_node_count: number;
+ import_edge_count: number;
+ importing_file_count: number;
+ link_state: "linked" | "unlinked";
+}
+
+/** The full dependency registry for a repository. */
+export interface ExternalSystemsResponse {
+ items: ExternalSystemEntry[];
+ total: number;
+ prod_count: number;
+ dev_count: number;
+ ecosystems: string[];
+ manifests: string[];
+}
+
+/** Bounded package summaries for the external-dependency scan surface. */
+export interface ExternalSystemsSummaryResponse {
+ items: ExternalSystemSummaryEntry[];
+ returned: number;
+ total_packages: number;
+ limit: number;
+ offset: number;
+ truncated: boolean;
+ scope: "primary" | "all";
+ excluded_declarations: number;
+ total_declarations: number;
+ runtime_packages: number;
+ dev_only_packages: number;
+ observed_packages: number;
+ linked_packages: number;
+ unlinked_packages: number;
+ linked_without_imports: number;
+ ecosystems: string[];
+ manifest_count: number;
+}
+
+export interface FeedbackRequest {
+ /** One of ui_ux, bug, feature_request, other */
+ category: string;
+ message: string;
+ email?: string | null;
+ page_url?: string | null;
+}
+
+export interface FeedbackResponse {
+ ok: boolean;
+}
+
+/** One file's score over time. ``points`` is empty on thin history. */
+export interface FileHealthTrendResponse {
+ file_path: string;
+ points?: FileTrendPointResponse[];
+ current?: number | null;
+ previous?: number | null;
+ delta?: number | null;
+ unclamped_delta?: number | null;
+ declining?: boolean;
+ snapshot_count?: number;
+}
+
+export interface FileTrendPointResponse {
+ taken_at?: string | null;
+ score: number;
+ unclamped_score: number;
+}
+
+export interface FindingStatusUpdate {
+ /** open | acknowledged | resolved | false_positive */
+ status: string;
+}
+
+/** One changed file's recency-weighted bug-fix record. */
+export interface FixHistoryFileResponse {
+ path: string;
+ churn: number;
+ fix_pressure: number;
+}
+
+/**
+ * Bug-fix history of the files a change touches.
+ *
+ * The size-orthogonal half of the answer: unlike ``score``, none of this grows
+ * with the diff. ``density`` is the churn-weighted mean fix pressure of the
+ * touched files; ``percentile`` ranks it against the same measure over the
+ * repository's own recent commits, and is ``None`` when there is no sample to
+ * rank against.
+ */
+export interface FixHistoryResponse {
+ available: boolean;
+ density: number;
+ percentile: number | null;
+ files: FixHistoryFileResponse[];
+}
+
+/** Optional per-call overrides for the enrichment provider/model. */
+export interface GenerateCodeRequest {
+ provider?: string | null;
+ model?: string | null;
+}
+
+/** Generated refactored code + diff for one plan, with the self-check. */
+export interface GenerateCodeResponse {
+ suggestion_id?: string | null;
+ refactoring_type: string;
+ file_path: string;
+ target_symbol: string;
+ content: string;
+ diff: string;
+ provider: string;
+ model: string;
+ cached: boolean;
+ input_tokens: number;
+ output_tokens: number;
+ validation?: Record<string, unknown>;
+ spans?: Record<string, unknown>[];
+}
+
+/**
+ * Body for the generate + estimate endpoints.
+ *
+ * ``cascade`` is optional: left unset it resolves to ``none`` for a ranked
+ * selection (the ranked set is already a coherent slice) and ``dependents`` for
+ * an explicit one, matching the CLI ``generate`` defaults.
+ */
+export interface GenerateRequestBody {
+ selection?: GenerateSelectionBody;
+ cascade?: "none" | "dependents" | "full" | null;
+ style?: string | null;
+}
+
+/**
+ * Which pages a generate request targets.
+ *
+ * Two selection philosophies, kept distinct exactly as the CLI keeps them:
+ *
+ * - **Explicit**: ``all`` / ``unwritten`` / ``stale``, an explicit ``page_ids``
+ * list, or every page under a ``path_prefix`` — the caller names the pages.
+ * - **Ranked** (``kind="ranked"``): write the most important slice by the same
+ * importance model ``repowise init`` uses, sized by ``coverage_pct`` (a
+ * fraction in ``(0, 1]``; ``1.0`` == everything) or ``top_n`` (a target page
+ * count, not exact). The two are mutually exclusive.
+ *
+ * The two philosophies cannot be combined; :func:`_validate_generate_selection`
+ * enforces it with an actionable 400.
+ */
+export interface GenerateSelectionBody {
+ kind?: "all" | "unwritten" | "stale" | "page_ids" | "path_prefix" | "ranked";
+ page_ids?: string[] | null;
+ path_prefix?: string | null;
+ coverage_pct?: number | null;
+ top_n?: number | null;
+}
+
+export interface GitMetadataResponse {
+ file_path: string;
+ commit_count_total: number;
+ commit_count_90d: number;
+ commit_count_30d: number;
+ first_commit_at: string | null;
+ last_commit_at: string | null;
+ primary_owner_name: string | null;
+ primary_owner_email: string | null;
+ primary_owner_commit_pct: number | null;
+ recent_owner_name: string | null;
+ recent_owner_commit_pct: number | null;
+ top_authors: Record<string, unknown>[];
+ significant_commits: Record<string, unknown>[];
+ co_change_partners: Record<string, unknown>[];
+ is_hotspot: boolean;
+ is_stable: boolean;
+ churn_percentile: number;
+ age_days: number;
+ bus_factor: number;
+ contributor_count: number;
+ lines_added_90d: number;
+ lines_deleted_90d: number;
+ avg_commit_size: number;
+ commit_categories: Record<string, unknown>;
+ merge_commit_count_90d: number;
+ change_entropy?: number;
+ change_entropy_pct?: number;
+ prior_defect_count?: number;
+ fix_symbol_counts?: Record<string, unknown>;
+ bug_magnet?: boolean;
+ last_fix_at?: string | null;
+ temporal_hotspot_score?: number | null;
+ commit_count_capped?: boolean;
+ original_path?: string | null;
+ test_gap?: boolean | null;
+ agent_commit_count?: number;
+ agent_authored_pct?: number | null;
+ agent_tier_counts?: Record<string, unknown>;
+}
+
+export interface GitSummaryResponse {
+ total_files: number;
+ hotspot_count: number;
+ stable_count: number;
+ average_churn_percentile: number;
+ top_owners: Record<string, unknown>[];
+}
+
+/** Slim decision reference so lists can render titles, not UUIDs. */
+export interface GoverningDecisionRef {
+ id: string;
+ title: string;
+ status: string;
+}
+
+export interface GraphEdgeResponse {
+ source: string;
+ target: string;
+ imported_names: string[];
+ edge_type?: string | null;
+ confidence?: number | null;
+}
+
+export interface GraphExportResponse {
+ nodes: GraphNodeResponse[];
+ links: GraphEdgeResponse[];
+ truncated?: boolean;
+ total_node_count?: number | null;
+ dead_total?: number | null;
+ dead_in_view?: number | null;
+ hot_total?: number | null;
+ hot_in_view?: number | null;
+}
+
+export interface GraphMetricsResponse {
+ target: string;
+ node_type: string;
+ pagerank: number;
+ pagerank_percentile: number;
+ betweenness: number;
+ betweenness_percentile: number;
+ community_id: number;
+ community_label: string | null;
+ is_entry_point: boolean;
+ in_degree: number;
+ out_degree: number;
+ entry_point_score?: number | null;
+ kind?: string | null;
+ file?: string | null;
+}
+
+export interface GraphNodeResponse {
+ node_id: string;
+ node_type: string;
+ language: string;
+ symbol_count: number;
+ pagerank: number;
+ betweenness: number;
+ community_id: number;
+ is_test?: boolean;
+ is_entry_point?: boolean;
+ has_doc?: boolean;
+ is_hotspot?: boolean;
+ churn_percentile?: number | null;
+ is_dead?: boolean;
+ dead_confidence?: number | null;
+ has_decision?: boolean;
+ primary_owner?: string | null;
+}
+
+export interface HTTPValidationError {
+ detail?: ValidationError[];
+}
+
+/**
+ * Shields-compatible badge fields for the JSON endpoint.
+ *
+ * ``schemaVersion`` is camelCase because the Shields endpoint protocol
+ * requires that exact key; without it every embedded badge renders as
+ * "invalid response" instead of the score.
+ */
+export interface HealthBadgeResponse {
+ schemaVersion?: number;
+ label: string;
+ message: string;
+ color: string;
+ band: string;
+}
+
+/** One file's movement between the last two snapshots. */
+export interface HealthFileDelta {
+ file_path: string;
+ before: number;
+ after: number;
+ delta: number;
+}
+
+/** One biomarker finding, as the table and drawer read it. */
+export interface HealthFindingResponse {
+ id: string;
+ file_path: string;
+ biomarker_type: string;
+ severity: string;
+ function_name?: string | null;
+ line_start?: number | null;
+ line_end?: number | null;
+ health_impact: number;
+ reason?: string | null;
+ details?: Record<string, unknown>;
+ status: string;
+ dimension?: string;
+}
+
+/**
+ * A listed finding, resolved to the symbol a tool can look up.
+ *
+ * ``None`` when the finding is file-level, or no symbol matched its span,
+ * so the UI degrades to the file page.
+ */
+export interface HealthFindingWithSymbolResponse {
+ id: string;
+ file_path: string;
+ biomarker_type: string;
+ severity: string;
+ function_name?: string | null;
+ line_start?: number | null;
+ line_end?: number | null;
+ health_impact: number;
+ reason?: string | null;
+ details?: Record<string, unknown>;
+ status: string;
+ dimension?: string;
+ symbol_id?: string | null;
+}
+
+export interface HealthResponse {
+ status: string;
+ db: string;
+ version: string;
+}
+
+export interface HealthTrendAlert {
+ kind: string;
+ metric: string;
+ current: number;
+ baseline?: number | null;
+ delta: number;
+ message: string;
+}
+
+/** One snapshot in the repo-level history, newest first. */
+export interface HealthTrendKpiRow {
+ taken_at?: string | null;
+ hotspot_health: number;
+ average_health: number;
+ worst_performer_path?: string | null;
+ worst_performer_score?: number | null;
+}
+
+export interface HealthTrendResponse {
+ history?: HealthTrendKpiRow[];
+ summary: HealthTrendSummary;
+ alerts?: HealthTrendAlert[];
+ file_deltas?: HealthFileDelta[];
+ file_deltas_total?: number;
+ snapshot_count?: number;
+}
+
+export interface HealthTrendSummary {
+ current_hotspot_health: number;
+ current_average_health: number;
+ previous_hotspot_health?: number | null;
+ previous_average_health?: number | null;
+ hotspot_delta?: number | null;
+ average_delta?: number | null;
+}
+
+/** One file in the triage queue, ranked by impact over effort. */
+export interface HealthWorkItem {
+ file_path: string;
+ score: number;
+ nloc: number;
+ module?: string | null;
+ primary_biomarker: string;
+ primary_severity: string;
+ primary_reason?: string | null;
+ primary_function?: string | null;
+ primary_line_start?: number | null;
+ primary_line_end?: number | null;
+ primary_suggestion?: string | null;
+ primary_finding_id: string;
+ total_impact: number;
+ finding_count: number;
+ biomarkers?: string[];
+ effort_bucket: string;
+ impact_per_effort: number;
+}
+
+export interface HealthWorkQueueResponse {
+ targets?: HealthWorkItem[];
+ total?: number;
+}
+
+export interface HotFilesGraphResponse {
+ nodes: HotFilesNodeResponse[];
+ links: GraphEdgeResponse[];
+}
+
+export interface HotFilesNodeResponse {
+ node_id: string;
+ node_type: string;
+ language: string;
+ symbol_count: number;
+ pagerank: number;
+ betweenness: number;
+ community_id: number;
+ is_test?: boolean;
+ is_entry_point?: boolean;
+ has_doc?: boolean;
+ is_hotspot?: boolean;
+ churn_percentile?: number | null;
+ is_dead?: boolean;
+ dead_confidence?: number | null;
+ has_decision?: boolean;
+ primary_owner?: string | null;
+ commit_count: number;
+}
+
+export interface HotspotResponse {
+ file_path: string;
+ commit_count_total?: number;
+ commit_count_90d: number;
+ commit_count_30d: number;
+ churn_percentile: number;
+ temporal_hotspot_score?: number | null;
+ primary_owner: string | null;
+ primary_owner_commit_pct?: number | null;
+ recent_owner_name?: string | null;
+ recent_owner_commit_pct?: number | null;
+ is_hotspot: boolean;
+ is_stable: boolean;
+ bus_factor: number;
+ contributor_count: number;
+ lines_added_90d: number;
+ lines_deleted_90d: number;
+ avg_commit_size: number;
+ commit_categories: Record<string, unknown>;
+ merge_commit_count_90d?: number;
+ commit_count_capped?: boolean;
+ age_days?: number;
+ last_commit_at?: string | null;
+ change_entropy?: number;
+ change_entropy_pct?: number;
+ prior_defect_count?: number;
+ bug_magnet?: boolean;
+ last_fix_at?: string | null;
+ original_path?: string | null;
+}
+
+/**
+ * The 202 payload every background-job launch returns.
+ *
+ * ``stream_token`` authorizes ``/api/jobs/{job_id}/stream`` directly, so a
+ * client can attach without a second round-trip or an API key in the query
+ * string.
+ */
+export interface JobAcceptedResponse {
+ job_id: string;
+ status?: string;
+ stream_token: string;
+}
+
+export interface JobResponse {
+ id: string;
+ repository_id: string;
+ status: string;
+ provider_name: string;
+ model_name: string;
+ total_pages: number;
+ completed_pages: number;
+ failed_pages: number;
+ current_level: number;
+ error_message: string | null;
+ config: Record<string, unknown>;
+ created_at: string;
+ updated_at: string;
+ started_at: string | null;
+ finished_at: string | null;
+ stream_token?: string | null;
+}
+
+export interface KnowledgeMapOwner {
+ email: string;
+ name: string;
+ files_owned: number;
+ percentage: number;
+}
+
+export interface KnowledgeMapResponse {
+ top_owners: KnowledgeMapOwner[];
+ knowledge_silos: KnowledgeMapSilo[];
+ onboarding_targets: KnowledgeMapTarget[];
+}
+
+export interface KnowledgeMapSilo {
+ file_path: string;
+ owner_email: string;
+ owner_pct: number;
+}
+
+export interface KnowledgeMapTarget {
+ path: string;
+ pagerank: number;
+ doc_words: number;
+}
+
+/**
+ * Per-tool MCP savings (``tool`` with the ``mcp:`` prefix stripped).
+ *
+ * ``kind`` distinguishes a ``"counterfactual"`` saving (the answer replaced raw
+ * file exploration — recorded in the savings ledger) from a ``"truncation"``
+ * drop (content trimmed past the response budget — the only signal for tools
+ * without a counterfactual estimator yet).
+ */
+export interface McpDropGroup {
+ tool: string;
+ events: number;
+ tokens: number;
+ kind?: string;
+}
+
+/** One tool in the configurable surface, with the flags a UI needs. */
+export interface McpToolInfo {
+ name: string;
+ description: string;
+ tier: string;
+ default: boolean;
+ default_single_repo: boolean;
+ default_workspace: boolean;
+ eligible: boolean;
+ eligible_single_repo: boolean;
+ eligible_workspace: boolean;
+ requires_workspace: boolean;
+ enabled: boolean;
+ recipes?: McpToolRecipeInfo[];
+ artifact_type: string;
+ presentation: string;
+ safety: string;
+ evidence_basis: string;
+}
+
+export interface McpToolRecipeInfo {
+ name: string;
+ call: string;
+ requires: string[];
+}
+
+/** The full tool surface for a repo plus its current override. */
+export interface McpToolSurfaceResponse {
+ repo_id?: string | null;
+ is_workspace: boolean;
+ override?: string[] | string | null;
+ tools: McpToolInfo[];
+}
+
+export interface ModuleEdgeResponse {
+ source: string;
+ target: string;
+ edge_count: number;
+}
+
+export interface ModuleGraphResponse {
+ nodes: ModuleNodeResponse[];
+ edges: ModuleEdgeResponse[];
+}
+
+/** Single-module deep view with breakdowns. */
+export interface ModuleHealthDetail {
+ module_path: string;
+ file_count: number;
+ symbol_count: number;
+ hotspot_count: number;
+ dead_code_count: number;
+ dead_code_lines: number;
+ avg_churn_percentile: number;
+ median_bus_factor: number;
+ min_bus_factor: number;
+ primary_owner: string | null;
+ primary_owner_pct: number;
+ is_silo: boolean;
+ decision_count: number;
+ doc_coverage_pct: number;
+ health_score: number;
+ owners: ModuleHealthOwner[];
+ top_hotspots: string[];
+ governing_decisions: GoverningDecisionRef[];
+ contributor_count: number;
+}
+
+export interface ModuleHealthOwner {
+ name: string;
+ email: string | null;
+ file_count: number;
+ pct: number;
+}
+
+/** One row in the per-module health rollup. */
+export interface ModuleHealthSummary {
+ module_path: string;
+ file_count: number;
+ symbol_count: number;
+ hotspot_count: number;
+ dead_code_count: number;
+ dead_code_lines: number;
+ avg_churn_percentile: number;
+ median_bus_factor: number;
+ min_bus_factor: number;
+ primary_owner: string | null;
+ primary_owner_pct: number;
+ is_silo: boolean;
+ decision_count: number;
+ doc_coverage_pct: number;
+ health_score: number;
+}
+
+export interface ModuleNodeResponse {
+ module_id: string;
+ file_count: number;
+ symbol_count: number;
+ avg_pagerank: number;
+ doc_coverage_pct: number;
+ hotspot_count?: number;
+ dead_count?: number;
+ has_decision?: boolean;
+ primary_owner?: string | null;
+}
+
+export interface NeighboringCommunity {
+ community_id: number;
+ label: string;
+ cross_edge_count: number;
+}
+
+export interface NodeSearchResult {
+ node_id: string;
+ language: string;
+ symbol_count: number;
+}
+
+/** Acknowledgement for a mutation with nothing else to report. */
+export interface OkResponse {
+ ok?: boolean;
+}
+
+/**
+ * How much coding-agent activity lands on the files this person owns.
+ *
+ * Aggregated from the per-file agent-provenance rollup (GitMetadata) over
+ * the owner's primary-owned files — agent identity per commit lives on the
+ * commits surface, the per-file rollup only carries counts and tiers.
+ */
+export interface OwnerAgentCollab {
+ files_with_agent_commits: number;
+ agent_commit_count: number;
+ agent_share_pct: number | null;
+ tier_counts?: Record<string, unknown>;
+}
+
+export interface OwnerCoAuthor {
+ name: string;
+ email: string | null;
+ shared_files: number;
+ co_change_strength: number;
+}
+
+export interface OwnerFileEntry {
+ file_path: string;
+ commit_count_90d: number;
+ churn_percentile: number;
+ bus_factor: number;
+ is_hotspot: boolean;
+ last_commit_at: string | null;
+ primary_owner_commit_pct: number | null;
+}
+
+/** One row in the engineering-leader-facing owners directory. */
+export interface OwnerListEntry {
+ key: string;
+ name: string;
+ email: string | null;
+ files_owned: number;
+ hotspots_owned: number;
+ silo_modules: number;
+ dead_code_files_owned: number;
+ dead_code_lines_owned: number;
+ commit_count_90d: number;
+ last_commit_at: string | null;
+ bus_factor_risk_files: number;
+}
+
+export interface OwnerModuleRollup {
+ module_path: string;
+ file_count: number;
+ hotspot_count: number;
+ dominant_pct: number;
+}
+
+export interface OwnerProfileResponse {
+ key: string;
+ name: string;
+ email: string | null;
+ files_owned: number;
+ hotspots_owned: number;
+ silo_modules: number;
+ dead_code_files_owned: number;
+ dead_code_lines_owned: number;
+ commit_count_90d: number;
+ last_commit_at: string | null;
+ first_commit_at: string | null;
+ bus_factor_risk_files: number;
+ lines_added_90d_est: number;
+ lines_deleted_90d_est: number;
+ modules: OwnerModuleRollup[];
+ top_files: OwnerFileEntry[];
+ files_touched_total?: number;
+ co_authors: OwnerCoAuthor[];
+ co_authors_total?: number;
+ commit_categories: Record<string, unknown>;
+ agent_collab?: OwnerAgentCollab | null;
+}
+
+export interface OwnershipEntry {
+ module_path: string;
+ primary_owner: string | null;
+ owner_pct: number | null;
+ file_count: number;
+ is_silo: boolean;
+}
+
+/** PATCH body for /lookup/notes. ``None`` clears the note. */
+export interface PageNotesUpdate {
+ human_notes?: string | null;
+}
+
+export interface PageResponse {
+ id: string;
+ repository_id: string;
+ page_type: string;
+ title: string;
+ target_path: string;
+ source_hash: string;
+ model_name: string;
+ provider_name: string;
+ input_tokens: number;
+ output_tokens: number;
+ cached_tokens: number;
+ generation_level: number;
+ version: number;
+ confidence: number;
+ freshness_status: string;
+ content_chars: number;
+ layer_id?: string | null;
+ layer_name?: string | null;
+ is_chapter?: boolean;
+ human_notes?: string | null;
+ parent_page_id?: string | null;
+ display_order?: number;
+ section_number?: string | null;
+ structural_key?: string | null;
+ created_at: string;
+ updated_at: string;
+ content: string;
+ metadata: Record<string, unknown>;
+}
+
+export interface PageVersionResponse {
+ id: string;
+ page_id: string;
+ version: number;
+ page_type: string;
+ title: string;
+ content: string;
+ source_hash: string;
+ model_name: string;
+ provider_name: string;
+ input_tokens: number;
+ output_tokens: number;
+ confidence: number;
+ archived_at: string;
+}
+
+export interface Paginated_CommitResponse_ {
+ items: CommitResponse[];
+ total: number;
+ has_more: boolean;
+ next_offset?: number | null;
+}
+
+export interface Paginated_HotspotResponse_ {
+ items: HotspotResponse[];
+ total: number;
+ has_more: boolean;
+ next_offset?: number | null;
+}
+
+export interface Paginated_ModuleHealthSummary_ {
+ items: ModuleHealthSummary[];
+ total: number;
+ has_more: boolean;
+ next_offset?: number | null;
+}
+
+export interface Paginated_OwnerListEntry_ {
+ items: OwnerListEntry[];
+ total: number;
+ has_more: boolean;
+ next_offset?: number | null;
+}
+
+export interface Paginated_OwnershipEntry_ {
+ items: OwnershipEntry[];
+ total: number;
+ has_more: boolean;
+ next_offset?: number | null;
+}
+
+export interface Paginated_SymbolResponse_ {
+ items: SymbolResponse[];
+ total: number;
+ has_more: boolean;
+ next_offset?: number | null;
+}
+
+/** One provider in the catalog, as the settings picker renders it. */
+export interface ProviderEntry {
+ id: string;
+ name: string;
+ models?: string[];
+ default_model?: string | null;
+ configured?: boolean;
+}
+
+export interface ProviderStatusResponse {
+ active: ActiveProviderSelection;
+ providers?: ProviderEntry[];
+}
+
+/**
+ * Outcome of the live single-provider smoke test.
+ *
+ * A failed probe reports ``ok=False`` with ``error`` set rather than raising,
+ * so the settings UI renders a clean error state.
+ */
+export interface ProviderValidationResponse {
+ ok: boolean;
+ provider?: string | null;
+ model?: string | null;
+ error?: string | null;
+}
+
+/** One page of composed opportunities, with facets and the rollup. */
+export interface RefactoringOpportunitiesResponse {
+ items?: Record<string, unknown>[];
+ total?: number;
+ offset?: number;
+ has_more?: boolean;
+ next_offset?: number | null;
+ facets?: Record<string, Record<string, number>>;
+ summary?: Record<string, unknown> | null;
+ ignored_arguments?: Record<string, string> | null;
+}
+
+/**
+ * One opportunity: its ordered steps, evidence, validation and plans.
+ *
+ * ``extra="allow"``: the base row is composed in core and this response
+ * spreads an evidence block over it, so the declared keys are the stable
+ * part and anything else passes through rather than being dropped.
+ */
+export interface RefactoringOpportunityDetailResponse {
+ resolved: boolean;
+ steps?: Record<string, unknown>[];
+ steps_total?: number;
+ steps_emitted?: number;
+ steps_reduced_reason?: string | null;
+ steps_next_cursor?: number | null;
+ validation_profiles?: Record<string, unknown>[];
+ affected_files?: string[];
+ lead_finding_ids?: string[];
+ next_actions?: Record<string, unknown>[];
+ plans?: Record<string, unknown>[] | null;
+ ordering_note?: string | null;
+}
+
+/** What one opportunity-level triage decision wrote. */
+export interface RefactoringOpportunityStatusResponse {
+ opportunity_id: string;
+ status: string;
+ steps_updated: number;
+ status_changed_at?: string | null;
+}
+
+/** The finding-triage vocabulary, applied to a whole opportunity. */
+export interface RefactoringOpportunityStatusUpdate {
+ /** open | acknowledged | resolved | false_positive */
+ status: string;
+}
+
+/** Bounded product page; the legacy targets response remains unpaged. */
+export interface RefactoringPlanPageResponse {
+ items: RefactoringPlanResponse[];
+ total: number;
+ has_more: boolean;
+ next_offset: number | null;
+ summary: RefactoringSummary;
+ structural_leads: RefactoringPlanResponse[];
+}
+
+/**
+ * One ranked refactoring plan, with its open ``plan`` / ``evidence`` /
+ * ``blast_radius`` dicts re-hydrated from the persisted ``*_json`` columns.
+ */
+export interface RefactoringPlanResponse {
+ id: string;
+ refactoring_type: string;
+ file_path: string;
+ target_symbol: string;
+ line_start?: number | null;
+ line_end?: number | null;
+ plan?: Record<string, unknown>;
+ evidence?: Record<string, unknown>;
+ impact_delta?: number;
+ effort_bucket?: string;
+ blast_radius?: Record<string, unknown>;
+ confidence?: string;
+ source_biomarker?: string;
+ benefit?: number;
+ leverage?: number;
+ cost?: number;
+ risk?: number;
+ rank_score?: number;
+ dependents?: number;
+ file_nloc?: number;
+ file_weighted_deficit?: number;
+ validation?: Record<string, unknown>;
+}
+
+/** What one plan-level triage decision wrote. */
+export interface RefactoringPlanStatusResponse {
+ id: string;
+ public_id?: string | null;
+ status: string;
+ status_reason?: string | null;
+ status_changed_at?: string | null;
+}
+
+/** The repository rollup and its one lead. */
+export interface RefactoringRollupResponse {
+ summary?: Record<string, unknown>;
+ directive?: Record<string, unknown>;
+}
+
+/** The opt-in code-generation switches, mirrored from ``refactoring.llm``. */
+export interface RefactoringSettings {
+ enabled?: boolean;
+ provider?: string | null;
+ model?: string | null;
+}
+
+/** Same shape and vocabulary as health finding triage — one triage system. */
+export interface RefactoringStatusUpdate {
+ /** open | acknowledged | resolved | false_positive */
+ status: string;
+}
+
+export interface RefactoringSummary {
+ total: number;
+ by_type: RefactoringTypeCount[];
+ files_total?: number | null;
+ structural_total?: number | null;
+ performance_total?: number | null;
+ small_effort_total?: number | null;
+ health_recovery_total?: number | null;
+ negligible_health_total?: number | null;
+ best_health_gain?: number | null;
+}
+
+export interface RefactoringTargetsResponse {
+ summary: RefactoringSummary;
+ plans: RefactoringPlanResponse[];
+}
+
+export interface RefactoringTypeCount {
+ type: string;
+ count: number;
+}
+
+export interface RepoCreate {
+ name: string;
+ local_path: string;
+ url?: string;
+ default_branch?: string;
+ settings?: Record<string, unknown> | null;
+ index?: boolean;
+}
+
+/** What a repository delete removed, for the confirmation toast. */
+export interface RepoDeletedResponse {
+ ok?: boolean;
+ deleted_pages?: number;
+}
+
+export interface RepoResponse {
+ id: string;
+ name: string;
+ url: string;
+ local_path: string;
+ default_branch: string;
+ head_commit: string | null;
+ settings: Record<string, unknown>;
+ created_at: string;
+ updated_at: string;
+ workspace_alias?: string | null;
+ workspace_status?: string | null;
+ is_primary?: boolean | null;
+ docs_enabled?: boolean | null;
+ docs_mode?: "none" | "deterministic" | "llm" | null;
+ docs_skip_reason?: string | null;
+ run_mode?: string | null;
+ git_tier?: string | null;
+ initial_job_id?: string | null;
+}
+
+export interface RepoStatsResponse {
+ file_count: number;
+ symbol_count: number;
+ entry_point_count: number;
+ doc_coverage_pct: number;
+ freshness_score: number;
+ dead_export_count: number;
+}
+
+/**
+ * One repository's headline figures, for the multi-repo dashboard.
+ *
+ * Every count here is a count of the thing its name says. ``file_count`` in
+ * particular is file nodes only: ``/stats`` counts every ``graph_nodes`` row,
+ * which on this repo is 38,813 against 3,600 actual files, because symbol
+ * nodes live in the same table.
+ */
+export interface RepoSummaryRow {
+ id: string;
+ name: string;
+ local_path: string;
+ updated_at?: string | null;
+ status?: string;
+ file_count?: number;
+ symbol_count?: number;
+ entry_point_count?: number;
+ doc_page_count?: number;
+ doc_fresh_page_count?: number;
+ dead_export_count?: number;
+ tracked_file_count?: number;
+ hotspot_count?: number;
+ average_health?: number | null;
+ hotspot_health?: number | null;
+ health_taken_at?: string | null;
+ indexed_commit?: string | null;
+ live_head?: string | null;
+ index_behind?: boolean | null;
+}
+
+export interface RepoUpdate {
+ name?: string | null;
+ url?: string | null;
+ default_branch?: string | null;
+ settings?: Record<string, unknown> | null;
+}
+
+export interface ReposSummaryResponse {
+ repos: RepoSummaryRow[];
+}
+
+export interface ReviewerEntry {
+ email: string;
+ files: number;
+ ownership_pct: number;
+}
+
+export interface ReviewerSuggestion {
+ name: string;
+ email: string | null;
+ score: number;
+ recent_commits: number;
+ owned_paths: string[];
+ co_change_paths: string[];
+ reasons: string[];
+}
+
+export interface ReviewerSuggestionsResponse {
+ paths: string[];
+ suggestions: ReviewerSuggestion[];
+}
+
+export interface RiskAuthority {
+ authoritative_for: string;
+ primary_fields: string[];
+ primary_basis: string;
+ fallback_field: string;
+ fallback_basis: string;
+ score_role: string;
+}
+
+export interface RiskCalibration {
+ status: string;
+ source?: string | null;
+ calibrated_at?: string | null;
+ population?: string | null;
+ granularity?: string | null;
+}
+
+export interface RiskCompatibilityField {
+ deprecated: boolean;
+ replacement: string;
+ equivalent_value: boolean;
+ historical_meaning: string;
+}
+
+/** One feature's signed contribution to a commit's change-risk logit. */
+export interface RiskDriverResponse {
+ feature: string;
+ value: number | null;
+ contribution: number;
+ label: string;
+}
+
+/** One bin of the repo's supporting 0-10 diff-shape score distribution. */
+export interface RiskHistogramBucket {
+ start: number;
+ end: number;
+ count: number;
+}
+
+/**
+ * Change-risk report for a live ``base..head`` git range.
+ *
+ * Scored on demand from the working tree rather than the indexed commit
+ * table, so it works for ranges that haven't been indexed yet (an open PR
+ * branch). Mirrors ``repowise risk <base>..<head> --format json`` field for
+ * field.
+ */
+export interface RiskRangeResponse {
+ base: string;
+ head: string;
+ fix_history: FixHistoryResponse;
+ risk_authority: RiskAuthority;
+ score: number;
+ score_measures: string;
+ score_unit: string;
+ risk_percentile: number | null;
+ review_priority: string | null;
+ classification: string | null;
+ fallback_band: string | null;
+ is_fix: boolean;
+ features: ChangeFeaturesResponse;
+ drivers: RiskDriverResponse[];
+}
+
+export interface RiskScalarSemantics {
+ field: string;
+ kind: string;
+ unit: string;
+ range: RiskScaleRange | null;
+ measures: string;
+ deterministic?: boolean;
+ calibration?: RiskCalibration | null;
+ authoritative?: boolean | null;
+ authoritative_for_change_review?: boolean | null;
+ runtime_breakage_probability?: boolean | null;
+ formula?: string | null;
+ thresholds?: Record<string, number> | null;
+ band_thresholds?: Record<string, number> | null;
+ component_fields?: Record<string, Record<string, unknown>> | null;
+}
+
+export interface RiskScaleRange {
+ minimum: number | null;
+ maximum: number | null;
+}
+
+export interface SearchResultResponse {
+ page_id: string;
+ title: string;
+ page_type: string;
+ target_path: string;
+ score: number;
+ snippet: string;
+ search_type: string;
+}
+
+export interface SecurityFindingResponse {
+ id: number;
+ file_path: string;
+ kind: string;
+ severity: string;
+ snippet: string | null;
+ detected_at: string;
+ line_number: number | null;
+ line_verified: boolean;
+ commit_sha: string | null;
+ commit_at: string | null;
+ found_in_history: boolean;
+}
+
+export interface SetActiveProviderRequest {
+ provider: string;
+ model?: string | null;
+ repo_id?: string | null;
+}
+
+export interface SetApiKeyRequest {
+ api_key: string;
+ repo_id?: string | null;
+}
+
+/**
+ * Transparent breakdown of the composite importance score so the UI can
+ * explain *why* a symbol ranks where it does. All fields are normalized to
+ * [0, 1] except booleans.
+ */
+export interface SymbolImportanceComponents {
+ file_pagerank?: number;
+ visibility_factor?: number;
+ complexity_norm?: number;
+ kind_boost?: number;
+ is_entry_point?: boolean;
+}
+
+export interface SymbolNodeSummary {
+ symbol_id: string;
+ name: string;
+ kind: string;
+ file: string;
+ start_line?: number | null;
+ signature?: string | null;
+}
+
+/**
+ * One relation kind, on one side of a symbol, with its true total.
+ *
+ * `total` is counted unbounded while `rows` is capped, so a surface can say
+ * "12 of 1,516" instead of silently rendering the cap as the count.
+ */
+export interface SymbolRelationGroup {
+ direction: "in" | "out";
+ edge_type: string;
+ group: string;
+ total: number;
+ rows: CallerCalleeEntry[];
+}
+
+export interface SymbolResponse {
+ id: string;
+ repository_id: string;
+ file_path: string;
+ symbol_id: string;
+ name: string;
+ qualified_name: string;
+ kind: string;
+ signature: string;
+ start_line: number;
+ end_line: number;
+ docstring: string | null;
+ visibility: string;
+ is_async: boolean;
+ complexity_estimate: number;
+ language: string;
+ parent_name: string | null;
+ importance_score?: number | null;
+ importance_components?: SymbolImportanceComponents | null;
+ file_pagerank?: number | null;
+ is_entry_point?: boolean | null;
+ file_churn_percentile?: number | null;
+ file_is_hotspot?: boolean | null;
+ blame_mod_count?: number | null;
+ blame_recent_mod_count?: number | null;
+ blame_median_author_time?: number | null;
+ blame_owner_name?: string | null;
+ blame_owner_line_pct?: number | null;
+ fix_count?: number | null;
+}
+
+export interface TestImpactAnalysis {
+ status: "available" | "partial" | "degraded";
+ stale: boolean;
+ partial: boolean;
+ degraded: boolean;
+ basis_categories: ("measured" | "inferred")[];
+}
+
+export interface TestImpactCoverage {
+ status: "available" | "partial" | "unavailable" | "degraded";
+ reason?: string | null;
+ map_present: boolean;
+ pair_count: number;
+ test_count: number;
+ source_file_count: number;
+ changed_files_total: number;
+ changed_files_with_measured_tests: number;
+ changed_files_without_measured_tests: number;
+ ingested_at?: string | null;
+ source_format?: string | null;
+ freshness: TestImpactFreshness;
+}
+
+export interface TestImpactEvidence {
+ basis: "measured" | "inferred";
+ source_file: string;
+ via: "coverage-map" | "call-graph" | "import-graph";
+ source_format?: string | null;
+}
+
+export interface TestImpactFile {
+ source_file: string;
+ status: "measured" | "inferred" | "unknown";
+ measured_tests: string[];
+ measured_tests_total: number;
+ inferred_tests: string[];
+ inferred_tests_total: number;
+}
+
+export interface TestImpactFreshness {
+ status: "current" | "stale" | "unknown";
+ reason?: string | null;
+ ingested_commit?: string | null;
+ indexed_commit?: string | null;
+}
+
+export interface TestImpactInference {
+ status: "available" | "degraded";
+ reason?: string | null;
+ changed_files_total: number;
+ changed_files_with_candidates: number;
+ candidates_before_dedup: number;
+}
+
+export interface TestImpactResponse {
+ recommendations: TestRecommendation[];
+ recommendations_total: number;
+ recommendations_emitted: number;
+ recommendations_truncated: boolean;
+ recommendations_omitted: number;
+ recommendations_by_primary_basis: Record<string, number>;
+ files: TestImpactFile[];
+ files_total: number;
+ files_without_measured_tests: string[];
+ unknown_files: string[];
+ coverage: TestImpactCoverage;
+ inference: TestImpactInference;
+ analysis: TestImpactAnalysis;
+}
+
+export interface TestRecommendation {
+ test_id: string;
+ test_file?: string | null;
+ repository_id: string;
+ repository: string;
+ basis: "measured" | "inferred";
+ bases: ("measured" | "inferred")[];
+ source_files: string[];
+ evidence: TestImpactEvidence[];
+}
+
+export interface TransitiveEntry {
+ path: string;
+ depth: number;
+}
+
+/**
+ * Persist a new ``mcp.tools`` override for a repo.
+ *
+ * ``tools`` accepts the same shapes as the config block: a list of explicit
+ * names or ``+``/``-`` deltas, the string ``"all"``, or ``null``/empty to
+ * clear the override and fall back to the default surface.
+ */
+export interface UpdateMcpToolsRequest {
+ repo_id: string;
+ tools?: string[] | string | null;
+}
+
+export interface ValidationError {
+ loc: (string | number)[];
+ msg: string;
+ type: string;
+ input?: unknown;
+ ctx?: Record<string, unknown>;
+}
+
+/** Server version, PyPI freshness, and (optional) per-repo store status. */
+export interface VersionResponse {
+ server_version: string;
+ latest_version?: string | null;
+ update_available?: boolean | null;
+ upgrade_command: string;
+ store_format_version?: number | null;
+ store_compatible?: boolean | null;
+ reindex_recommended?: boolean;
+ reindex_command?: string | null;
+}
+
+export interface WebhookResponse {
+ event_id: string;
+ status?: string;
+}
+
+/** Architecture-complexity metrics over the system graph (Phase 6). */
+export interface WorkspaceArchitectureResponse {
+ node_count?: number;
+ structural_edge_count?: number;
+ propagation_cost?: number;
+ propagation_cost_pct?: number;
+ core_size?: number;
+ core_ratio?: number;
+ core_members?: string[];
+ cycle_count?: number;
+ conformance_violations?: number;
+ architecture_type?: string;
+ score?: number;
+ role_breakdown?: Record<string, number>;
+ roles?: WorkspaceNodeArchitectureRole[];
+ generated_at?: string;
+}
+
+export interface WorkspaceBlastRadiusResponse {
+ targets?: string[];
+ target_repos?: string[];
+ impacted?: WorkspaceImpactedNode[];
+ impacted_repos?: string[];
+ structural_count?: number;
+ behavioral_count?: number;
+ max_distance?: number;
+ total_impacted?: number;
+ unresolved_targets?: string[];
+}
+
+export interface WorkspaceBreakingChange {
+ kind: string;
+ severity: string;
+ contract_id: string;
+ contract_type: string;
+ provider_repo: string;
+ provider_file: string;
+ provider_symbol: string;
+ provider_symbol_id?: string | null;
+ provider_service?: string | null;
+ provider_node_id?: string;
+ detail: string;
+ field_name?: string | null;
+ old_value?: string | null;
+ new_value?: string | null;
+ impacted_consumers?: WorkspaceImpactedConsumer[];
+}
+
+export interface WorkspaceBreakingChangesResponse {
+ version?: number;
+ generated_at?: string | null;
+ changes?: WorkspaceBreakingChange[];
+ total?: number;
+ breaking_count?: number;
+ warning_count?: number;
+ impacted_repos?: string[];
+ impacted_services?: string[];
+ total_impacted_consumers?: number;
+}
+
+export interface WorkspaceCoChangeEntry {
+ source_repo: string;
+ source_file: string;
+ target_repo: string;
+ target_file: string;
+ strength: number;
+ frequency: number;
+ last_date: string;
+}
+
+export interface WorkspaceCoChangesResponse {
+ co_changes: WorkspaceCoChangeEntry[];
+ total: number;
+ total_mined?: number;
+}
+
+export interface WorkspaceConformanceResponse {
+ version?: number;
+ generated_at?: string | null;
+ rules_evaluated?: number;
+ violations?: WorkspaceConformanceViolation[];
+ cycles?: WorkspaceDependencyCycle[];
+ violation_count?: number;
+ cycle_count?: number;
+ total_cycles?: number;
+ violating_repos?: string[];
+}
+
+export interface WorkspaceConformanceViolation {
+ rule_source: string;
+ rule_target: string;
+ rule_description?: string;
+ source: string;
+ source_name: string;
+ target: string;
+ target_name: string;
+ edge_id: string;
+ edge_kind: string;
+ severity?: string;
+}
+
+/**
+ * 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.
+ */
+export interface WorkspaceContractDetail {
+ contract: WorkspaceContractEntry;
+ contract_schema?: Record<string, unknown> | null;
+ links?: WorkspaceContractLinkEntry[];
+ unmatched_reason?: string | null;
+}
+
+export interface WorkspaceContractEntry {
+ contract_id: string;
+ contract_type: string;
+ role: string;
+ repo: string;
+ file_path: string;
+ symbol_name: string;
+ confidence: number;
+ service?: string | null;
+ line?: number | null;
+ symbol_id?: string | null;
+ meta?: Record<string, unknown>;
+}
+
+export interface WorkspaceContractLinkEntry {
+ contract_id: string;
+ contract_type: string;
+ match_type: string;
+ confidence: number;
+ provider_repo: string;
+ provider_file: string;
+ provider_symbol: string;
+ consumer_repo: string;
+ consumer_file: string;
+ consumer_symbol: string;
+ provider_service?: string | null;
+ consumer_service?: string | null;
+ provider_symbol_id?: string | null;
+ consumer_symbol_id?: string | null;
+}
+
+export interface WorkspaceContractSummary {
+ total_contracts?: number;
+ total_links?: number;
+ by_type?: Record<string, number>;
+}
+
+export interface WorkspaceContractsResponse {
+ contracts: WorkspaceContractEntry[];
+ links: WorkspaceContractLinkEntry[];
+ total_contracts: number;
+ total_links: number;
+ by_type?: Record<string, number>;
+}
+
+export interface WorkspaceCrossRepoSummary {
+ co_change_count?: number;
+ package_dep_count?: number;
+ top_connections?: Record<string, unknown>[];
+}
+
+export interface WorkspaceDependencyCycle {
+ nodes?: string[];
+ edge_ids?: string[];
+ length?: number;
+}
+
+export interface WorkspaceExtractionDiagnostics {
+ total_providers?: number;
+ total_consumers?: number;
+ total_links?: number;
+ weak_link_count?: number;
+ repo_breakdown?: WorkspaceRepoDiagnostics[];
+ unmatched_consumers?: WorkspaceUnmatchedConsumer[];
+ unmatched_by_reason?: Record<string, number>;
+ orphan_providers?: WorkspaceOrphanProvider[];
+ providers_by_layer?: Record<string, number>;
+ consumers_by_layer?: Record<string, number>;
+ http_consumers_unresolved?: number;
+ http_consumer_coverage?: number | null;
+}
+
+export interface WorkspaceGraphEdge {
+ source: string;
+ target: string;
+ type: string;
+ strength?: number;
+ label?: string | null;
+}
+
+export interface WorkspaceGraphNode {
+ repo_id: string;
+ name: string;
+ file_count?: number;
+ coverage_pct?: number;
+ health_score?: number;
+ health_score_source?: string;
+ top_language?: string;
+}
+
+export interface WorkspaceGraphResponse {
+ nodes?: WorkspaceGraphNode[];
+ edges?: WorkspaceGraphEdge[];
+}
+
+export interface WorkspaceImpactedConsumer {
+ repo: string;
+ service?: string | null;
+ node_id: string;
+ file: string;
+ symbol: string;
+ symbol_id?: string | null;
+ match_type?: string;
+ confidence?: number;
+}
+
+export interface WorkspaceImpactedNode {
+ id: string;
+ repo: string;
+ name: string;
+ kind?: string;
+ distance: number;
+ score: number;
+ structural: boolean;
+ edge_kinds?: string[];
+}
+
+export interface WorkspaceNodeArchitectureRole {
+ id: string;
+ repo?: string;
+ name?: string;
+ visibility_fan_in?: number;
+ visibility_fan_out?: number;
+ role?: string;
+}
+
+export interface WorkspaceOrphanProvider {
+ repo: string;
+ file_path: string;
+ contract_id: string;
+ contract_type: string;
+}
+
+export interface WorkspaceRepoDiagnostics {
+ repo: string;
+ providers_by_type?: Record<string, number>;
+ consumers_by_type?: Record<string, number>;
+ provider_count?: number;
+ consumer_count?: number;
+ providers_by_layer?: Record<string, number>;
+ consumers_by_layer?: Record<string, number>;
+ http_consumers_unresolved?: number;
+}
+
+export interface WorkspaceRepoEntry {
+ alias: string;
+ path: string;
+ is_primary?: boolean;
+ indexed_at?: string | null;
+ last_commit_at_index?: string | null;
+ repo_id?: string | null;
+ file_count?: number;
+ symbol_count?: number;
+ page_count?: number;
+ doc_coverage_pct?: number;
+ hotspot_count?: number;
+ health_score?: number | null;
+ status?: string;
+ docs_enabled?: boolean;
+ docs_skip_reason?: string | null;
+}
+
+export interface WorkspaceResponse {
+ is_workspace: boolean;
+ workspace_root?: string | null;
+ workspace_name?: string | null;
+ repos?: WorkspaceRepoEntry[];
+ default_repo?: string | null;
+ cross_repo_summary?: WorkspaceCrossRepoSummary | null;
+ contract_summary?: WorkspaceContractSummary | null;
+}
+
+export interface WorkspaceSyncResponse {
+ results: WorkspaceSyncResult[];
+ accepted?: number;
+ skipped?: number;
+ errors?: number;
+}
+
+export interface WorkspaceSyncResult {
+ alias: string;
+ job_id?: string | null;
+ repo_id?: string | null;
+ status: string;
+ reason?: string | null;
+}
+
+export interface WorkspaceSystemEdge {
+ id: string;
+ source: string;
+ target: string;
+ kind: string;
+ match_type: string;
+ confidence?: number;
+ weight?: number;
+ structural?: boolean;
+ contract_refs?: string[];
+}
+
+export interface WorkspaceSystemGraphResponse {
+ version?: number;
+ generated_at?: string;
+ nodes?: WorkspaceSystemNode[];
+ edges?: WorkspaceSystemEdge[];
+ diagnostics?: WorkspaceExtractionDiagnostics;
+}
+
+export interface WorkspaceSystemNode {
+ id: string;
+ repo: string;
+ service_path?: string | null;
+ name: string;
+ kind?: string;
+ provider_count?: number;
+ consumer_count?: number;
+ contract_types?: string[];
+ is_orphan_provider?: boolean;
+ is_orphan_consumer?: boolean;
+ is_isolated?: boolean;
+}
+
+export interface WorkspaceUnmatchedConsumer {
+ repo: string;
+ file_path: string;
+ contract_id: string;
+ contract_type: string;
+ reason: string;
+}
+
+export interface ZoomMapResponse {
+ root_id: string;
+ project_name: string;
+ total_files: number;
+ unclaimed_files?: number;
+ max_depth: number;
+ truncated?: boolean;
+ nodes: ZoomNodeResponse[];
+ relations: ZoomRelationResponse[];
+}
+
+export interface ZoomMetricsResponse {
+ file_count?: number;
+ descendant_count?: number;
+ hotspot_count?: number;
+ dead_count?: number;
+ entry_point_count?: number;
+ on_flow_count?: number;
+}
+
+export interface ZoomNodeResponse {
+ id: string;
+ parent_id?: string | null;
+ level: number;
+ kind: string;
+ name: string;
+ path?: string;
+ children?: string[];
+ importance?: number;
+ sibling_rank?: number;
+ metrics?: ZoomMetricsResponse;
+ summary?: string;
+ language?: string | null;
+ page_id?: string;
+ health_score?: number | null;
+ is_entry_point?: boolean;
+ is_hotspot?: boolean;
+ is_dead?: boolean;
+ is_test?: boolean;
+ on_flow?: boolean;
+}
+
+export interface ZoomRelationResponse {
+ parent_id: string;
+ source_id: string;
+ target_id: string;
+ label?: string;
+ edge_count?: number;
+ coupling?: string;
+}
diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.ts
index 46774c1c9..2dae11469 100644
--- a/packages/types/src/workspace.ts
+++ b/packages/types/src/workspace.ts
@@ -147,7 +147,11 @@ export interface SystemGraph {
// ---------------------------------------------------------------------------
/** Why a consumer contract never formed a cross-repo link. */
-export type UnmatchedReason = "no_provider" | "internal_only" | "unlinked";
+export type UnmatchedReason =
+ | "no_provider"
+ | "internal_only"
+ | "unlinked"
+ | "external_host";
export interface RepoDiagnostics {
repo: string;
@@ -284,6 +288,8 @@ export interface BreakingChangeConsumer {
/** The exact consumer file that calls the changed contract. */
file: string;
symbol: string;
+ /** Looked-up id for `symbol`; `null` when the consumer did not resolve to one. */
+ symbol_id?: string | null;
match_type: string;
confidence: number;
}
@@ -297,6 +303,8 @@ export interface BreakingChange {
provider_repo: string;
provider_file: string;
provider_symbol: string;
+ /** Looked-up id for `provider_symbol`; `null` when it did not resolve to one. */
+ provider_symbol_id?: string | null;
provider_service: string | null;
/** System-graph node id of the changed provider. */
provider_node_id: string;
diff --git a/packages/ui/__tests__/chat/change-risk-artifact.test.tsx b/packages/ui/__tests__/chat/change-risk-artifact.test.tsx
index dd15805bf..d7df5bd94 100644
--- a/packages/ui/__tests__/chat/change-risk-artifact.test.tsx
+++ b/packages/ui/__tests__/chat/change-risk-artifact.test.tsx
@@ -36,6 +36,7 @@ const data: RiskReportArtifactData = {
health_delta: {
status: "available",
explanation: "Compared 3 changed files on both sides.",
+ basis: "both_sides_analyzed",
introduced: 1,
worsened: 0,
resolved: 2,
diff --git a/scripts/generate_http_types.py b/scripts/generate_http_types.py
new file mode 100644
index 000000000..e50955dea
--- /dev/null
+++ b/scripts/generate_http_types.py
@@ -0,0 +1,211 @@
+"""Generate the TypeScript HTTP contract from the live FastAPI schema.
+
+The wire types under ``packages/types/src`` are hand-written and were drifting
+from the Pydantic models that actually serialize: a field added on one side
+went missing on the other silently, because both sides degrade rather than
+throw. This emits the HTTP half from ``/openapi.json`` so that half cannot
+drift, and leaves the hand-written artifact/UI/domain types alone.
+
+Run ``python scripts/generate_http_types.py`` to refresh, ``--check`` to fail
+when the checked-in file is stale.
+
+Determinism, since CI diffs the output: schema names are sorted, property order
+follows the model's declaration order (Pydantic preserves it), and ``info`` is
+never read — it carries the release version, which would otherwise register as
+drift on every version bump.
+"""
+
+from __future__ import annotations
+
+import argparse
+import pathlib
+import re
+import sys
+from typing import Any
+
+_OUT = pathlib.Path(__file__).resolve().parents[1] / "packages/types/src/generated/http.ts"
+
+_PRIMITIVES = {
+ "string": "string",
+ "integer": "number",
+ "number": "number",
+ "boolean": "boolean",
+ "null": "null",
+}
+
+_HEADER = """// Generated from the FastAPI application's OpenAPI schema. Do not edit.
+//
+// Regenerate with: python scripts/generate_http_types.py
+// CI fails when this file and the live schema disagree.
+//
+// Scope: the HTTP boundary only. Artifact, UI and other non-wire domain types
+// stay hand-written in the sibling modules.
+//
+// `?` mirrors the schema's `required` list, which states what a request may
+// omit. A response field with a server-side default is still always sent.
+"""
+
+
+def _identifier(name: str) -> str:
+ """A schema name as a TypeScript identifier."""
+ cleaned = re.sub(r"[^0-9A-Za-z_]", "_", name)
+ return f"_{cleaned}" if cleaned[:1].isdigit() else cleaned
+
+
+def _literal(value: Any) -> str:
+ if value is None:
+ return "null"
+ if isinstance(value, bool):
+ return "true" if value else "false"
+ if isinstance(value, (int, float)):
+ return str(value)
+ return '"' + str(value).replace("\\", "\\\\").replace('"', '\\"') + '"'
+
+
+def _type_of(schema: Any) -> str:
+ """One OpenAPI schema node as a TypeScript type expression."""
+ if not isinstance(schema, dict) or not schema:
+ return "unknown"
+
+ ref = schema.get("$ref")
+ if ref:
+ return _identifier(ref.rsplit("/", 1)[-1])
+
+ if "const" in schema:
+ return _literal(schema["const"])
+
+ if "enum" in schema:
+ members = [_literal(v) for v in schema["enum"]]
+ return " | ".join(members) if members else "never"
+
+ for combinator, joiner in (("anyOf", " | "), ("oneOf", " | "), ("allOf", " & ")):
+ if combinator in schema:
+ parts = [_type_of(s) for s in schema[combinator]]
+ # A one-armed union is the arm; ``string | null`` must keep both.
+ unique = list(dict.fromkeys(parts))
+ if not unique:
+ return "unknown"
+ if len(unique) == 1:
+ return unique[0]
+ if joiner == " & ":
+ # ``A | B & C`` binds as ``A | (B & C)``, so a union arm inside
+ # an intersection has to be parenthesized.
+ unique = [f"({part})" if "|" in part else part for part in unique]
+ return joiner.join(unique)
+
+ kind = schema.get("type")
+ if isinstance(kind, list):
+ return " | ".join(dict.fromkeys(_PRIMITIVES.get(k, "unknown") for k in kind))
+
+ if kind == "array":
+ prefix = schema.get("prefixItems")
+ if prefix:
+ return "[" + ", ".join(_type_of(entry) for entry in prefix) + "]"
+ item = _type_of(schema.get("items", {}))
+ # Only a union needs the parentheses; a generic does not.
+ return f"({item})[]" if "|" in item or "&" in item else f"{item}[]"
+
+ if kind == "object" or "properties" in schema:
+ if "properties" in schema:
+ return _object_literal(schema)
+ extra = schema.get("additionalProperties")
+ if isinstance(extra, dict) and extra:
+ return f"Record<string, {_type_of(extra)}>"
+ if extra is False:
+ return "Record<string, never>"
+ return "Record<string, unknown>"
+
+ return _PRIMITIVES.get(kind, "unknown")
+
+
+def _object_literal(schema: dict[str, Any]) -> str:
+ """An inline object schema, for properties that were not given a name."""
+ required = set(schema.get("required") or ())
+ fields = [
+ f"{_property_key(name)}{'' if name in required else '?'}: {_type_of(spec)}"
+ for name, spec in (schema.get("properties") or {}).items()
+ ]
+ return "{ " + "; ".join(fields) + " }" if fields else "Record<string, unknown>"
+
+
+def _property_key(name: str) -> str:
+ return name if re.fullmatch(r"[A-Za-z_$][\w$]*", name) else _literal(name)
+
+
+def _docstring(schema: dict[str, Any]) -> list[str]:
+ text = (schema.get("description") or "").strip()
+ if not text:
+ return []
+ lines = [line.rstrip() for line in text.splitlines()]
+ if len(lines) == 1:
+ return [f"/** {lines[0]} */"]
+ return ["/**", *(f" * {line}".rstrip() for line in lines), " */"]
+
+
+def _declaration(name: str, schema: dict[str, Any]) -> str:
+ ident = _identifier(name)
+ out: list[str] = _docstring(schema)
+
+ if "properties" not in schema:
+ # An alias: a union, an enum, an array or a bare record under a name.
+ out.append(f"export type {ident} = {_type_of(schema)};")
+ return "\n".join(out)
+
+ required = set(schema.get("required") or ())
+ out.append(f"export interface {ident} {{")
+ for prop, spec in (schema.get("properties") or {}).items():
+ for line in _docstring(spec if isinstance(spec, dict) else {}):
+ out.append(f" {line}")
+ optional = "" if prop in required else "?"
+ out.append(f" {_property_key(prop)}{optional}: {_type_of(spec)};")
+ out.append("}")
+ return "\n".join(out)
+
+
+def render(openapi: dict[str, Any]) -> str:
+ schemas = (openapi.get("components") or {}).get("schemas") or {}
+ seen: dict[str, str] = {}
+ for name in sorted(schemas):
+ ident = _identifier(name)
+ first = seen.setdefault(ident, name)
+ if first != name:
+ raise ValueError(f"{name!r} and {first!r} both emit the identifier {ident!r}")
+ blocks = [_declaration(name, schemas[name]) for name in sorted(schemas)]
+ return _HEADER + "\n" + "\n\n".join(blocks) + "\n"
+
+
+def _live_schema() -> dict[str, Any]:
+ from repowise.server.app import create_app
+
+ return create_app().openapi()
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--check", action="store_true", help="Fail if the file is stale.")
+ args = parser.parse_args(argv)
+
+ rendered = render(_live_schema())
+
+ if args.check:
+ current = _OUT.read_text(encoding="utf-8") if _OUT.exists() else ""
+ if current != rendered:
+ print(
+ f"{_OUT.relative_to(_OUT.parents[4])} is stale.\n"
+ "Run: python scripts/generate_http_types.py",
+ file=sys.stderr,
+ )
+ return 1
+ return 0
+
+ _OUT.parent.mkdir(parents=True, exist_ok=True)
+ # newline="\n": the file is committed with an eol=lf attribute, so writing
+ # CRLF on Windows would make every local run look like drift.
+ with _OUT.open("w", encoding="utf-8", newline="\n") as handle:
+ handle.write(rendered)
+ print(f"wrote {_OUT}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/unit/analysis/test_external_systems_links.py b/tests/unit/analysis/test_external_systems_links.py
new file mode 100644
index 000000000..3bf8ed930
--- /dev/null
+++ b/tests/unit/analysis/test_external_systems_links.py
@@ -0,0 +1,284 @@
+"""Building declaration-to-node links from plain records, with no database.
+
+The folds took links as given; only the persistence layer knew how to build
+one. These pin the matcher's precedence and its ambiguity refusal, and prove a
+consumer holding nothing but declarations and graph nodes can reach the same
+folds the server does.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from types import SimpleNamespace
+
+from repowise.core.analysis.external_systems import (
+ ExternalSystemLink,
+ build_declaration_index,
+ build_declaration_links,
+ build_importing_files,
+ build_package_summary,
+ build_relationship_graph,
+ declaration_name_candidates,
+ resolve_declaration,
+)
+
+
+@dataclass
+class _Declaration:
+ """Stub mirroring the ExternalSystem columns the matcher reads."""
+
+ name: str
+ ecosystem: str = "npm"
+ declared_in: str = "package.json"
+
+
+@dataclass
+class _Node:
+ """Stub mirroring the GraphNode columns the matcher reads."""
+
+ node_id: str
+
+
+def _links(declarations, nodes) -> list[tuple[str, str, str]]:
+ built = build_declaration_links(declarations, nodes)
+ return [(link.node_id, link.ecosystem, link.name) for link in built]
+
+
+# --- candidate precedence -------------------------------------------------
+
+
+def test_candidates_lead_with_the_whole_name() -> None:
+ assert declaration_name_candidates("react")[0] == "react"
+
+
+def test_scoped_npm_subpath_falls_back_to_the_package() -> None:
+ assert declaration_name_candidates("@scope/pkg/sub") == (
+ "@scope/pkg/sub",
+ "@scope/pkg",
+ "@scope",
+ )
+
+
+def test_rust_and_python_paths_fall_back_to_their_root() -> None:
+ assert declaration_name_candidates("serde::de") == ("serde::de", "serde")
+ assert declaration_name_candidates("pkg.sub.mod") == ("pkg.sub.mod", "pkg")
+
+
+def test_candidates_are_deduplicated() -> None:
+ # The scoped rule and the whole name both yield "@scope/pkg"; it appears once.
+ assert declaration_name_candidates("@scope/pkg") == ("@scope/pkg", "@scope")
+
+
+# --- resolution -----------------------------------------------------------
+
+
+def test_exact_and_prefix_nodes_resolve_to_the_declaration() -> None:
+ declarations = [_Declaration("react"), _Declaration("serde", ecosystem="cargo")]
+ nodes = [
+ _Node("external:react"),
+ _Node("external:react/jsx-runtime"),
+ _Node("external:serde::de"),
+ ]
+
+ assert _links(declarations, nodes) == [
+ ("external:react", "npm", "react"),
+ ("external:react/jsx-runtime", "npm", "react"),
+ ("external:serde::de", "cargo", "serde"),
+ ]
+
+
+def test_a_name_two_ecosystems_declare_stays_unlinked() -> None:
+ declarations = [_Declaration("dup", ecosystem="npm"), _Declaration("dup", ecosystem="pypi")]
+
+ assert _links(declarations, [_Node("external:dup")]) == []
+
+
+def test_an_ecosystem_qualified_node_resolves_through_the_ambiguity() -> None:
+ declarations = [_Declaration("dup", ecosystem="npm"), _Declaration("dup", ecosystem="pypi")]
+
+ assert _links(declarations, [_Node("external:npm:dup")]) == [("external:npm:dup", "npm", "dup")]
+
+
+def test_an_ambiguous_candidate_refuses_rather_than_falling_through() -> None:
+ # The generic separators split at the *first* occurrence, so the only
+ # candidates for ``a/b/c`` are itself and ``a``. ``a`` is ambiguous, and
+ # matching it returns the refusal instead of resolving the collision.
+ declarations = [
+ _Declaration("a", ecosystem="npm"),
+ _Declaration("a", ecosystem="pypi"),
+ _Declaration("a/b/c", ecosystem="npm"),
+ ]
+
+ assert _links(declarations, [_Node("external:a/b/c")]) == [("external:a/b/c", "npm", "a/b/c")]
+ assert _links(declarations, [_Node("external:a/z")]) == []
+
+
+def test_only_a_scoped_npm_name_keeps_a_two_segment_fallback() -> None:
+ declarations = [_Declaration("@scope/pkg")]
+
+ assert _links(declarations, [_Node("external:@scope/pkg/sub")]) == [
+ ("external:@scope/pkg/sub", "npm", "@scope/pkg")
+ ]
+
+
+def test_undeclared_and_non_external_nodes_are_omitted() -> None:
+ declarations = [_Declaration("react")]
+ nodes = [_Node("external:unknown"), _Node("file:src/index.ts"), _Node("")]
+
+ assert _links(declarations, nodes) == []
+
+
+def test_node_order_is_preserved() -> None:
+ declarations = [_Declaration("react"), _Declaration("vue")]
+ nodes = [_Node("external:vue"), _Node("external:react")]
+
+ assert [node_id for node_id, _, _ in _links(declarations, nodes)] == [
+ "external:vue",
+ "external:react",
+ ]
+
+
+def test_a_declaration_without_a_name_is_skipped() -> None:
+ assert build_declaration_index([_Declaration("")]) == {}
+
+
+def test_resolve_declaration_reports_the_identity_not_a_link() -> None:
+ index = build_declaration_index([_Declaration("react")])
+
+ assert resolve_declaration("external:react", index) == ("npm", "react")
+ assert resolve_declaration("file:x", index) is None
+
+
+# --- record shapes --------------------------------------------------------
+
+
+def test_plain_dicts_link_the_same_as_objects() -> None:
+ declarations = [_Declaration("react"), _Declaration("serde", ecosystem="cargo")]
+ nodes = [_Node("external:react/jsx-runtime"), _Node("external:serde::de")]
+ as_dicts = [
+ {"name": d.name, "ecosystem": d.ecosystem, "declared_in": d.declared_in}
+ for d in declarations
+ ]
+
+ assert build_declaration_links(as_dicts, [{"node_id": n.node_id} for n in nodes]) == (
+ build_declaration_links(declarations, nodes)
+ )
+
+
+def test_links_are_the_record_shape_the_folds_consume() -> None:
+ link = ExternalSystemLink(node_id="external:react", ecosystem="npm", name="react")
+
+ assert link.as_dict() == {"node_id": "external:react", "ecosystem": "npm", "name": "react"}
+
+
+def test_a_consumer_folds_a_summary_from_declarations_and_nodes_alone() -> None:
+ """The seam's point: no session, no link table, same fold the server runs."""
+ declarations = [_Declaration("react"), _Declaration("jest")]
+ nodes = [_Node("external:react"), _Node("external:react/jsx-runtime")]
+ edges = [
+ {"source_path": "src/app.tsx", "target_node_id": "external:react"},
+ {"source_path": "src/ui.tsx", "target_node_id": "external:react/jsx-runtime"},
+ ]
+
+ links = build_declaration_links(declarations, nodes)
+ summary = build_package_summary(declarations, links, edges)
+
+ assert summary.total_packages == 2
+ react = next(entry for entry in summary.items if entry.name == "react")
+ assert react.importing_file_count == 2
+
+
+def test_one_package_declared_twice_in_one_ecosystem_stays_resolvable() -> None:
+ """The ambiguity rule must not fire on a monorepo's repeated manifest."""
+ declarations = [
+ _Declaration("react", declared_in="a/package.json"),
+ _Declaration("react", declared_in="b/package.json"),
+ ]
+
+ assert _links(declarations, [_Node("external:react")]) == [("external:react", "npm", "react")]
+
+
+def test_a_declaration_without_an_ecosystem_still_collides() -> None:
+ declarations = [_Declaration("http", ecosystem=""), _Declaration("http", ecosystem="pub")]
+
+ assert _links(declarations, [_Node("external:http")]) == []
+
+
+def test_attribute_rows_link_the_same_as_dataclasses() -> None:
+ """The third record shape the fold adapter claims: a plain attribute row."""
+ declarations = [_Declaration("react")]
+ nodes = [_Node("external:react")]
+ rows = [SimpleNamespace(name="react", ecosystem="npm", declared_in="package.json")]
+
+ assert build_declaration_links(rows, [SimpleNamespace(node_id="external:react")]) == (
+ build_declaration_links(declarations, nodes)
+ )
+
+
+def test_the_relationship_folds_run_on_links_built_without_a_database() -> None:
+ declarations = [_Declaration("react")]
+ nodes = [_Node("external:react")]
+ edges = [
+ {"source_path": "src/app.tsx", "target_node_id": "external:react", "community_id": 1},
+ {"source_path": "src/ui.tsx", "target_node_id": "external:react", "community_id": 1},
+ ]
+ links = build_declaration_links(declarations, nodes)
+
+ graph = build_relationship_graph(declarations, links, edges, "npm:react")
+ assert graph is not None
+ assert graph.nodes
+
+ files = build_importing_files(declarations, links, edges, "npm:react", "community:1")
+ assert files is not None
+ assert files.total == 2
+
+
+def test_the_sql_link_map_resolves_the_same_nodes_as_the_plain_record_path() -> None:
+ """The two paths share the index; this pins that they still agree.
+
+ The CRUD writer resolves a node to a row id and this module resolves it to
+ an identity, so only equality of the *linked set* is comparable — which is
+ exactly what would diverge if one copy of the rule drifted.
+ """
+ from repowise.core.persistence.crud.external_systems import build_external_system_link_map
+
+ systems = [
+ {"name": "react", "ecosystem": "npm", "declared_in": "package.json"},
+ {"name": "serde", "ecosystem": "cargo", "declared_in": "Cargo.toml"},
+ {"name": "dup", "ecosystem": "npm", "declared_in": "package.json"},
+ {"name": "dup", "ecosystem": "pypi", "declared_in": "pyproject.toml"},
+ {"name": "@scope/pkg", "ecosystem": "npm", "declared_in": "package.json"},
+ ]
+ id_map = {(s["name"], s["declared_in"]): index for index, s in enumerate(systems, start=1)}
+ node_ids = [
+ "external:react",
+ "external:react/jsx-runtime",
+ "external:serde::de",
+ "external:dup",
+ "external:npm:dup",
+ "external:@scope/pkg/sub",
+ "external:unknown",
+ ]
+
+ name_to_id = build_external_system_link_map(systems, id_map)
+ sql_linked = {
+ node_id
+ for node_id in node_ids
+ if next(
+ (
+ name_to_id[name]
+ for name in declaration_name_candidates(node_id.removeprefix("external:"))
+ if name in name_to_id
+ ),
+ None,
+ )
+ is not None
+ }
+ plain_linked = {
+ link.node_id
+ for link in build_declaration_links(
+ systems, [{"node_id": node_id} for node_id in node_ids]
+ )
+ }
+
+ assert sql_linked == plain_linked
diff --git a/tests/unit/server/test_generated_http_types.py b/tests/unit/server/test_generated_http_types.py
new file mode 100644
index 000000000..8e9f0c26a
--- /dev/null
+++ b/tests/unit/server/test_generated_http_types.py
@@ -0,0 +1,107 @@
+"""The generated HTTP contract must match the schema the app actually serves.
+
+This is the gate that makes generation worth having: a Pydantic model changed
+without regenerating fails here, rather than surfacing later as a TypeScript
+type that quietly disagrees with the wire.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import pathlib
+
+import pytest
+
+_ROOT = pathlib.Path(__file__).resolve().parents[3]
+_SCRIPT = _ROOT / "scripts/generate_http_types.py"
+_GENERATED = _ROOT / "packages/types/src/generated/http.ts"
+
+
+def _generator():
+ spec = importlib.util.spec_from_file_location("_generate_http_types", _SCRIPT)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
[email protected](scope="module")
+def generator():
+ return _generator()
+
+
+def test_the_committed_contract_matches_the_live_schema(generator) -> None:
+ from repowise.server.app import create_app
+
+ rendered = generator.render(create_app().openapi())
+
+ assert _GENERATED.read_text(encoding="utf-8") == rendered, (
+ "packages/types/src/generated/http.ts is stale. "
+ "Run: python scripts/generate_http_types.py"
+ )
+
+
+def test_generation_is_deterministic(generator) -> None:
+ from repowise.server.app import create_app
+
+ schema = create_app().openapi()
+
+ assert generator.render(schema) == generator.render(schema)
+
+
+def test_the_release_version_is_not_baked_into_the_contract(generator) -> None:
+ """``info.version`` moves every release; reading it would fake drift."""
+ from repowise.server.app import create_app
+
+ schema = create_app().openapi()
+ baseline = generator.render(schema)
+ schema["info"]["version"] = "999.999.999"
+
+ assert generator.render(schema) == baseline
+
+
+ ("schema", "expected"),
+ [
+ ({"type": "string"}, "string"),
+ ({"type": "integer"}, "number"),
+ ({"anyOf": [{"type": "string"}, {"type": "null"}]}, "string | null"),
+ ({"type": "array", "items": {"type": "string"}}, "string[]"),
+ (
+ {"type": "array", "items": {"anyOf": [{"type": "string"}, {"type": "null"}]}},
+ "(string | null)[]",
+ ),
+ ({"$ref": "#/components/schemas/RepoResponse"}, "RepoResponse"),
+ ({"type": "object", "additionalProperties": {"type": "integer"}}, "Record<string, number>"),
+ ({"type": "object", "additionalProperties": True}, "Record<string, unknown>"),
+ ({"enum": ["a", "b"]}, '"a" | "b"'),
+ # An intersection arm that is itself a union has to keep its brackets:
+ # ``A | B & C`` binds as ``A | (B & C)``.
+ (
+ {
+ "allOf": [
+ {"anyOf": [{"type": "string"}, {"type": "null"}]},
+ {"type": "object", "additionalProperties": {"type": "string"}},
+ ]
+ },
+ "(string | null) & Record<string, string>",
+ ),
+ (
+ {"type": "array", "prefixItems": [{"type": "string"}, {"type": "integer"}]},
+ "[string, number]",
+ ),
+ ({"type": "object", "additionalProperties": False}, "Record<string, never>"),
+ ({"const": "fixed"}, '"fixed"'),
+ ({}, "unknown"),
+ ],
+)
+def test_schema_nodes_map_to_typescript(generator, schema, expected) -> None:
+ assert generator._type_of(schema) == expected
+
+
+def test_two_schema_names_cannot_share_one_identifier(generator) -> None:
+ """A sanitized collision would emit the same interface twice."""
+ import pytest as _pytest
+
+ with _pytest.raises(ValueError, match="identifier"):
+ generator.render({"components": {"schemas": {"A.B": {}, "A-B": {}}}})
diff --git a/tests/unit/server/test_health_badge.py b/tests/unit/server/test_health_badge.py
index 21be7367b..69f8ad79f 100644
--- a/tests/unit/server/test_health_badge.py
+++ b/tests/unit/server/test_health_badge.py
@@ -164,3 +164,23 @@ def test_churn_complexity_to_dict_wire_shape() -> None:
"score": 3.4,
"churn_percentile": 92.0,
}
+
+
+def test_the_badge_response_model_keeps_schema_version() -> None:
+ """Shields renders "invalid response" without it, so the model must carry it.
+
+ The route builds the payload as a plain dict, so a model that omitted this
+ key would drop it silently and break every embedded badge.
+ """
+ from repowise.server.schemas import HealthBadgeResponse
+
+ label, message, color, band = _badge_fields(9.0)
+ body = {
+ "schemaVersion": 1,
+ "label": label,
+ "message": message,
+ "color": color,
+ "band": band,
+ }
+
+ assert HealthBadgeResponse.model_validate(body).model_dump() == body
diff --git a/tests/unit/server/test_open_payload_models.py b/tests/unit/server/test_open_payload_models.py
new file mode 100644
index 000000000..66976a659
--- /dev/null
+++ b/tests/unit/server/test_open_payload_models.py
@@ -0,0 +1,80 @@
+"""The response models that must not drop a key they were not told about.
+
+Three payloads are assembled outside this layer: the composed refactoring
+opportunity, the stored rollup, and the chat artifact's per-tool result. Their
+models are deliberately open, and these pin that openness — a model that closed
+would silently drop the keys it did not declare, which is the failure the whole
+contract effort exists to prevent.
+"""
+
+from __future__ import annotations
+
+from repowise.server.schemas import (
+ ChatArtifactEnvelope,
+ RefactoringOpportunitiesResponse,
+ RefactoringOpportunityDetailResponse,
+)
+
+
+def test_opportunity_detail_carries_keys_it_never_declared() -> None:
+ payload = {
+ "resolved": True,
+ "steps": [{"plan_id": "p1"}],
+ "steps_total": 1,
+ "steps_emitted": 1,
+ "validation_profiles": [],
+ "affected_files": ["a.py"],
+ "lead_finding_ids": [],
+ "next_actions": [],
+ # Composed in core, and unknown to this module by design.
+ "opportunity_id": "o1",
+ "lead_type": "extract_method",
+ "evidence": [{"finding_id": "f1"}],
+ "evidence_total": 1,
+ }
+
+ dumped = RefactoringOpportunityDetailResponse.model_validate(payload).model_dump(
+ exclude_unset=True
+ )
+
+ assert [key for key in payload if key not in dumped] == []
+
+
+def test_the_opportunity_page_omits_ignored_arguments_until_there_are_some() -> None:
+ body = {
+ "items": [],
+ "total": 0,
+ "offset": 0,
+ "has_more": False,
+ "next_offset": None,
+ "facets": {},
+ "summary": None,
+ }
+
+ without = RefactoringOpportunitiesResponse.model_validate(body).model_dump(exclude_unset=True)
+ with_ignored = RefactoringOpportunitiesResponse.model_validate(
+ {**body, "ignored_arguments": {"effort": "unknown value"}}
+ ).model_dump(exclude_unset=True)
+
+ assert "ignored_arguments" not in without
+ assert with_ignored["ignored_arguments"] == {"effort": "unknown value"}
+
+
+def test_an_artifact_carries_whichever_tool_shape_it_holds() -> None:
+ envelope = ChatArtifactEnvelope.model_validate(
+ {
+ "id": "a1",
+ "version": 1,
+ "type": "risk",
+ "tool_name": "get_risk",
+ "title": "get_risk",
+ "presentation": "card",
+ "data": {"directive": {"status": "ok"}, "score": 4.2},
+ "evidence": {"basis": "extracted", "limits": {"collections": []}},
+ "pinned": False,
+ "created_at": "2026-01-01T00:00:00+00:00",
+ }
+ )
+
+ assert envelope.data["directive"] == {"status": "ok"}
+ assert envelope.evidence["limits"] == {"collections": []}
diff --git a/tests/unit/server/test_response_contract.py b/tests/unit/server/test_response_contract.py
new file mode 100644
index 000000000..1d7b11ce7
--- /dev/null
+++ b/tests/unit/server/test_response_contract.py
@@ -0,0 +1,146 @@
+"""Every JSON route names its response schema, or says why it does not.
+
+The TypeScript contract is generated from ``components.schemas``, so a route
+whose success response is an anonymous object contributes nothing to it and
+its shape goes back to being hand-copied. This walks the live application and
+fails when a route serves an unnamed body without an entry below.
+
+Two lists, and the difference matters. ``WAIVED`` is permanent: those routes do
+not serve a modelled JSON object at all. ``UNMODELLED`` is a shrinking backlog
+of routes that should be modelled and are not yet; a route may only leave it,
+never join it, and modelling one without deleting its line here fails too.
+"""
+
+from __future__ import annotations
+
+import re
+
+import pytest
+from fastapi.routing import APIRoute
+
+from repowise.server.app import create_app
+
+#: Routes that will never carry a named JSON schema, and why.
+WAIVED: dict[tuple[str, str], str] = {
+ ("POST", "/api/repos/{repo_id}/chat/messages"): "SSE stream",
+ ("GET", "/api/jobs/{job_id}/stream"): "SSE stream",
+ ("GET", "/api/repos/{repo_id}/export"): "streamed zip download",
+ ("GET", "/api/repos/{repo_id}/file-content"): "raw file body",
+ ("GET", "/api/repos/{repo_id}/health/badge.svg"): "image/svg+xml",
+ ("GET", "/api/graph/{repo_id}/c4/mermaid"): "text/plain diagram source",
+ ("GET", "/api/graph/{repo_id}/c4/structurizr"): "text/plain diagram source",
+ ("GET", "/metrics"): "Prometheus text exposition",
+ ("POST", "/api/providers/{provider_id}/key"): "204, no body",
+ ("DELETE", "/api/providers/{provider_id}/key"): "204, no body",
+ ("GET", "/api/pages"): (
+ "returns full or summary rows by ``fields``; the models serialize "
+ "themselves and FastAPI cannot coerce one shape into the other"
+ ),
+}
+
+#: Routes still serving an anonymous object. Delete a line when you model one.
+UNMODELLED: frozenset[tuple[str, str]] = frozenset(
+ {
+ ("GET", "/api/repos/{repo_id}/files"),
+ ("GET", "/api/repos/{repo_id}/files/{file_path}"),
+ ("POST", "/api/repos/{repo_id}/generate/estimate"),
+ ("GET", "/api/repos/{repo_id}/health/coverage"),
+ ("GET", "/api/repos/{repo_id}/health/files"),
+ ("GET", "/api/repos/{repo_id}/health/files/breakdown"),
+ ("GET", "/api/repos/{repo_id}/health/map"),
+ ("GET", "/api/repos/{repo_id}/health/modules"),
+ ("GET", "/api/repos/{repo_id}/health/overview"),
+ ("GET", "/api/repos/{repo_id}/health/performance-opportunities"),
+ ("GET", "/api/repos/{repo_id}/health/performance-opportunities/{opportunity_id}"),
+ (
+ "GET",
+ "/api/repos/{repo_id}/health/performance-opportunities/{opportunity_id}/findings",
+ ),
+ ("GET", "/api/repos/{repo_id}/health/tests-reaching"),
+ ("GET", "/api/repos/{repo_id}/overview-summary"),
+ ("POST", "/api/repos/{repo_id}/preflight"),
+ ("GET", "/api/repos/{repo_id}/stats/highlights"),
+ ("GET", "/api/symbols/detail"),
+ }
+)
+
+_SUCCESS_CODES = ("200", "201", "202", "204")
+_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE"})
+
+
+def _openapi_path(path: str) -> str:
+ """Drop Starlette's converter suffix; OpenAPI names the parameter alone."""
+ return re.sub(r"\{([^}:]+):[^}]+\}", r"{\1}", path)
+
+
+def _names_a_schema(schema: dict | None) -> bool:
+ """Whether a response body resolves to a schema the generator can emit."""
+ if not schema:
+ return False
+ if "$ref" in schema or "anyOf" in schema or "allOf" in schema:
+ return True
+ if schema.get("type") == "array":
+ return "$ref" in (schema.get("items") or {})
+ return False
+
+
[email protected](scope="module")
+def modelled_state() -> dict[tuple[str, str], bool]:
+ app = create_app()
+ schema = app.openapi()
+ state: dict[tuple[str, str], bool] = {}
+ for path, operations in schema["paths"].items():
+ for method, operation in operations.items():
+ if method.upper() not in _METHODS:
+ continue
+ responses = operation.get("responses", {})
+ code = next((c for c in _SUCCESS_CODES if c in responses), None)
+ if code is None:
+ continue
+ content = responses[code].get("content")
+ body = next(iter(content.values())).get("schema") if content else None
+ state[(method.upper(), path)] = _names_a_schema(body)
+ return state
+
+
+def test_every_route_is_modelled_waived_or_tracked(modelled_state) -> None:
+ unnamed = {route for route, modelled in modelled_state.items() if not modelled}
+ unaccounted = unnamed - set(WAIVED) - UNMODELLED
+
+ assert not unaccounted, (
+ "These routes serve an anonymous JSON body. Give each a response_model, "
+ "or add it to WAIVED with a reason: " + repr(sorted(unaccounted))
+ )
+
+
+def test_a_modelled_route_leaves_the_backlog(modelled_state) -> None:
+ fixed = {route for route in UNMODELLED if modelled_state.get(route)}
+
+ assert not fixed, (
+ "These routes are modelled now. Delete them from UNMODELLED: " + repr(sorted(fixed))
+ )
+
+
+def test_the_lists_only_name_live_routes(modelled_state) -> None:
+ stale = (set(WAIVED) | UNMODELLED) - set(modelled_state)
+
+ assert not stale, "These entries name no live route: " + repr(sorted(stale))
+
+
+def test_no_route_is_both_waived_and_tracked() -> None:
+ assert not set(WAIVED) & UNMODELLED
+
+
+def test_the_router_surface_is_fully_classified(modelled_state) -> None:
+ """Guards the walk itself: a router mounted but unseen would hide gaps."""
+ live = {
+ (method, _openapi_path(route.path))
+ for route in create_app().routes
+ if isinstance(route, APIRoute)
+ for method in route.methods
+ if method in _METHODS
+ }
+ # 204 routes carry no success body and are absent from the walk by design.
+ missing = live - set(modelled_state) - set(WAIVED)
+
+ assert not missing, repr(sorted(missing))
diff --git a/tests/unit/server/test_wire_vocabulary_parity.py b/tests/unit/server/test_wire_vocabulary_parity.py
index c2a75e440..bf51c38b7 100644
--- a/tests/unit/server/test_wire_vocabulary_parity.py
+++ b/tests/unit/server/test_wire_vocabulary_parity.py
@@ -1,9 +1,9 @@
-"""The two closed vocabularies cross a language boundary, so pin both ends.
+"""The closed vocabularies cross a language boundary, so pin both ends.
-``ResolutionOrigin`` and ``FlowTermination`` are declared in Python and copied
-into ``packages/types/src/graph.ts`` for the web surfaces. Nothing else makes
-the copies agree: a word added on one side renders as "unrecognised" forever on
-the other, silently, because both sides degrade rather than throw.
+``ResolutionOrigin``, ``FlowTermination`` and ``UnmatchedReason`` are declared
+in Python and copied into ``packages/types`` for the web surfaces. Nothing else
+makes the copies agree: a word added on one side renders as "unrecognised"
+forever on the other, silently, because both sides degrade rather than throw.
Ceiling: a regex read of the two TypeScript unions. It proves the *member sets*
match, not that the TS file parses.
@@ -16,17 +16,16 @@ import re
from repowise.core.analysis.execution_flows import FLOW_TERMINATION_VALUES
from repowise.core.ingestion.models import RESOLUTION_ORIGIN_VALUES
+from repowise.core.workspace.diagnostics import UNMATCHED_REASON_VALUES
-_TYPES = (
- pathlib.Path(__file__).resolve().parents[3] / "packages/types/src/graph.ts"
-)
+_TYPES_SRC = pathlib.Path(__file__).resolve().parents[3] / "packages/types/src"
-def _union_members(alias: str) -> set[str]:
+def _union_members(alias: str, module: str = "graph.ts") -> set[str]:
"""The string members of `export type <alias> = "a" | "b" | ...;`."""
- source = _TYPES.read_text(encoding="utf-8")
- match = re.search(rf"export type {alias} =(.*?);", source, re.DOTALL)
- assert match, f"{alias} is not declared in {_TYPES.name}"
+ path = _TYPES_SRC / module
+ match = re.search(rf"export type {alias} =(.*?);", path.read_text(encoding="utf-8"), re.DOTALL)
+ assert match, f"{alias} is not declared in {path.name}"
return set(re.findall(r'"([a-z_]+)"', match.group(1)))
@@ -36,3 +35,7 @@ def test_resolution_origin_union_matches_python() -> None:
def test_flow_termination_union_matches_python() -> None:
assert _union_members("FlowTermination") == set(FLOW_TERMINATION_VALUES)
+
+
+def test_unmatched_reason_union_matches_python() -> None:
+ assert _union_members("UnmatchedReason", "workspace.ts") == set(UNMATCHED_REASON_VALUES)
diff --git a/tests/unit/test_no_hotspot_health_copies.py b/tests/unit/test_no_hotspot_health_copies.py
index add10397e..ca5d28934 100644
--- a/tests/unit/test_no_hotspot_health_copies.py
+++ b/tests/unit/test_no_hotspot_health_copies.py
@@ -45,6 +45,7 @@ _PLUMBING: dict[str, str] = {
"repowise/core/persistence/stores/_sql_analysis.py": "passthrough to the crud writer",
"repowise/core/persistence/_interfaces/_analysis.py": "the store ABC's parameter name",
"repowise/server/schemas/repository.py": "the response field",
+ "repowise/server/schemas/code_health.py": "the trend response fields",
"alembic/versions/0019_code_health.py": "the migration that adds the column",
# --- writers: hand ``compute_kpis`` output to the snapshot ---------------
"repowise/core/pipeline/persist.py": "persists the KPI dict from the health report",