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.

10.0 KB
Raw Blame
import { apiDelete, apiGet, apiPost } from "./client";
import type {
  WorkspaceResponse,
  WorkspaceContractsResponse,
  WorkspaceContractDetail,
  WorkspaceCoChangesResponse,
  WorkspaceCoChangeStructure,
  WorkspaceGraphResponse,
  WorkspaceRepoRemovedResponse,
  WorkspaceSyncResponse,
  WorkspaceSystemGraphResponse,
  WorkspaceBlastRadiusResponse,
  WorkspaceLinksBetweenResponse,
  WorkspaceBreakingChangesResponse,
  WorkspaceConformanceResponse,
  WorkspaceArchitectureResponse,
  WorkspaceEstateResponse,
  WorkspaceTestImpactResponse,
  ExtractionDiagnostics,
} from "./types";

export async function getWorkspace(
  fetchOptions?: RequestInit,
): Promise<WorkspaceResponse> {
  return apiGet<WorkspaceResponse>("/api/workspace", undefined, fetchOptions);
}

export async function getWorkspaceContracts(opts?: {
  contract_type?: string;
  repo?: string;
  role?: string;
  /** Every whitespace-separated term must appear in the id, file, symbol, repo or service. */
  q?: string;
  /** true: only contracts on a matched link; false: only those on none. */
  linked?: boolean;
  /** false omits the link rows; `total_links` is still counted. */
  include_links?: boolean;
  limit?: number;
  offset?: number;
}): Promise<WorkspaceContractsResponse> {
  const params: Record<string, string> = {};
  if (opts?.contract_type) params.contract_type = opts.contract_type;
  if (opts?.repo) params.repo = opts.repo;
  if (opts?.role) params.role = opts.role;
  if (opts?.q) params.q = opts.q;
  if (opts?.linked != null) params.linked = String(opts.linked);
  if (opts?.include_links === false) params.include_links = "false";
  if (opts?.limit != null) params.limit = String(opts.limit);
  if (opts?.offset != null) params.offset = String(opts.offset);
  return apiGet<WorkspaceContractsResponse>("/api/workspace/contracts", params);
}

/**
 * One contract with its schema, its links, and its unmatched reason.
 *
 * Keyed by all three of `repo`, `file` and `id` because `id` alone is not
 * unique — several repos declare the same `http::GET::/user`. Query params
 * rather than a path segment because `file` carries slashes.
 */
export async function getWorkspaceContractDetail(
  opts: { repo: string; file: string; id: string },
  fetchOptions?: RequestInit,
): Promise<WorkspaceContractDetail> {
  return apiGet<WorkspaceContractDetail>(
    "/api/workspace/contracts/detail",
    { repo: opts.repo, file: opts.file, id: opts.id },
    fetchOptions,
  );
}

export async function getWorkspaceCoChanges(opts?: {
  repo?: string;
  min_strength?: number;
  limit?: number;
}): Promise<WorkspaceCoChangesResponse> {
  const params: Record<string, string> = {};
  if (opts?.repo) params.repo = opts.repo;
  if (opts?.min_strength != null) params.min_strength = String(opts.min_strength);
  if (opts?.limit != null) params.limit = String(opts.limit);
  return apiGet<WorkspaceCoChangesResponse>("/api/workspace/co-changes", params);
}

/** Contract links behind one co-changing file pair, fetched when its drawer opens. */
export async function getWorkspaceCoChangeStructure(pair: {
  source_repo: string;
  source_file: string;
  target_repo: string;
  target_file: string;
}): Promise<WorkspaceCoChangeStructure> {
  return apiGet<WorkspaceCoChangeStructure>("/api/workspace/co-changes/structure", pair);
}

export async function getWorkspaceGraph(): Promise<WorkspaceGraphResponse> {
  return apiGet<WorkspaceGraphResponse>("/api/workspace/graph");
}

/**
 * Why the cross-repo link count is what it is: providers and consumers found,
 * consumers that matched nothing and why, and providers nobody calls.
 *
 * These are the denominators the Contracts page needs. Without them the only
 * available totals are the filtered, paginated contract rows, which cannot say
 * how much of the workspace they represent.
 */
export async function getWorkspaceDiagnostics(
  fetchOptions?: RequestInit,
): Promise<ExtractionDiagnostics> {
  return apiGet<ExtractionDiagnostics>(
    "/api/workspace/diagnostics",
    undefined,
    fetchOptions,
  );
}

/**
 * The service-granular system graph (nodes = services, typed directed edges)
 * that the Live System Map renders. Thin pass-through over the persisted
 * `system_graph.json` artifact.
 *
 * `view: "map"` asks for the map's lean view: no `diagnostics` (read them from
 * `getWorkspaceDiagnostics`), no `contract_refs` on structural edges, and a
 * `ref_count` on every edge. A server without the view returns the full graph,
 * which has the same shape with those fields filled.
 */
export async function getWorkspaceSystemGraph(
  fetchOptions?: RequestInit,
  opts?: { view?: "map" },
): Promise<WorkspaceSystemGraphResponse> {
  return apiGet<WorkspaceSystemGraphResponse>(
    "/api/workspace/system-graph",
    opts?.view ? { view: opts.view } : undefined,
    fetchOptions,
  );
}

/**
 * Everything behind the edges between two service nodes (contract links,
 * package dependencies, co-changes), both directions, one page at a time.
 * Each end is resolved to its service server-side, the way the graph was built.
 */
export async function getWorkspaceLinksBetween(
  opts: {
    a: string;
    b: string;
    /** One edge kind: `http`, `grpc`, `event`, `db`, `package`, `co_change`... */
    kind?: string;
    /** Every whitespace-separated term must match the row's ids, files, symbols or packages. */
    q?: string;
    limit?: number;
    offset?: number;
  },
  fetchOptions?: RequestInit,
): Promise<WorkspaceLinksBetweenResponse> {
  const params: Record<string, string | number> = { a: opts.a, b: opts.b };
  if (opts.kind) params.kind = opts.kind;
  if (opts.q) params.q = opts.q;
  if (opts.limit != null) params.limit = opts.limit;
  if (opts.offset != null) params.offset = opts.offset;
  return apiGet<WorkspaceLinksBetweenResponse>(
    "/api/workspace/system-graph/links",
    params,
    fetchOptions,
  );
}

/**
 * Cross-repo blast radius from a service node (or repo alias): the downstream
 * services impacted if it changes, ranked by impact. Reads the same system
 * graph the map renders.
 */
export async function getWorkspaceBlastRadius(opts: {
  target: string;
  maxDepth?: number;
  includeBehavioral?: boolean;
}): Promise<WorkspaceBlastRadiusResponse> {
  const params: Record<string, string | number | boolean> = { target: opts.target };
  if (opts.maxDepth != null) params.max_depth = opts.maxDepth;
  if (opts.includeBehavioral != null) params.include_behavioral = opts.includeBehavioral;
  return apiGet<WorkspaceBlastRadiusResponse>("/api/workspace/blast-radius", params);
}

/**
 * Provider contract changes from the most recent update that break consumers
 * across repos, with the impacted consumer files. Optionally filter by provider
 * repo or severity.
 */
export async function getWorkspaceBreakingChanges(opts?: {
  repo?: string;
  severity?: "breaking" | "warning";
}): Promise<WorkspaceBreakingChangesResponse> {
  const params: Record<string, string> = {};
  if (opts?.repo) params.repo = opts.repo;
  if (opts?.severity) params.severity = opts.severity;
  return apiGet<WorkspaceBreakingChangesResponse>("/api/workspace/breaking-changes", params);
}

/**
 * Architecture conformance from the most recent update: dependency-rule
 * violations + dependency cycles over the system graph. Optionally filter to
 * findings involving one repo.
 */
export async function getWorkspaceConformance(opts?: {
  repo?: string;
}): Promise<WorkspaceConformanceResponse> {
  const params: Record<string, string> = {};
  if (opts?.repo) params.repo = opts.repo;
  return apiGet<WorkspaceConformanceResponse>("/api/workspace/conformance", params);
}

export async function getWorkspaceArchitecture(): Promise<WorkspaceArchitectureResponse> {
  return apiGet<WorkspaceArchitectureResponse>("/api/workspace/architecture");
}

/**
 * The estate report: repositories and services, the system map and its
 * evidence, contracts and dangling calls, health and churn per repo, the
 * riskiest seams and where to start. Built on request from the stored
 * workspace artifacts and every member index, so it takes about a second.
 */
export async function getWorkspaceEstate(
  fetchOptions?: RequestInit,
): Promise<WorkspaceEstateResponse> {
  return apiGet<WorkspaceEstateResponse>("/api/workspace/estate", undefined, fetchOptions);
}

/**
 * Trigger a re-sync (re-index) of the workspace. Pass ``repoAlias`` to
 * scope to one repo; otherwise the server fans out across every loaded
 * workspace repo. Returns one result per repo (accepted / skipped / error).
 */
export async function syncWorkspace(opts?: {
  repoAlias?: string;
  fullResync?: boolean;
}): Promise<WorkspaceSyncResponse> {
  const params: Record<string, string> = {};
  if (opts?.repoAlias) params.repo_alias = opts.repoAlias;
  if (opts?.fullResync) params.full_resync = "true";
  return apiPost<WorkspaceSyncResponse>(
    "/api/workspace/sync",
    undefined,
    undefined,
    params,
  );
}

/**
 * Which tests in the consumer repos guard a change to these provider files.
 *
 * Rows carry the basis they came from: `measured` when a coverage map recorded
 * the test against the consumer call site, `inferred` when the consumer call or
 * import graph reaches it. Links the join could not follow come back in
 * `unresolved` with a reason, so an empty answer always names its state.
 */
export async function getWorkspaceTestImpact(
  repo: string,
  files: string[],
  fetchOptions?: RequestInit,
): Promise<WorkspaceTestImpactResponse> {
  // `file` repeats once per changed path, so the query is built here: the
  // shared param helper sets each key once.
  const query = new URLSearchParams({ repo });
  for (const file of files) query.append("file", file);
  return apiGet<WorkspaceTestImpactResponse>(
    `/api/workspace/test-impact?${query.toString()}`,
    undefined,
    fetchOptions,
  );
}

/**
 * Remove a repository entry from `.repowise-workspace.yaml`.
 */
export async function removeWorkspaceRepo(
  alias: string,
  fetchOptions?: RequestInit,
): Promise<WorkspaceRepoRemovedResponse> {
  return apiDelete<WorkspaceRepoRemovedResponse>(
    `/api/workspace/repos/${encodeURIComponent(alias)}`,
    fetchOptions,
  );
}