import { z } from "zod"; import { CHANGE_SCOPES, HOTSPOT_METRICS, computeChanges, computeClusters, computeDeadExports, computeDependents, computeDuplication, computeFileContext, computeForces, computeGroups, computeHotspots, computeModuleStructure, computeOpportunities, computeOverview, computeProcesses, computeSearch, computeSymbolContext, impactAnalysis, renameSymbol, } from "../core/index.js"; import { computeBoundaries } from "../boundaries/index.js"; import { loadConfig } from "../config/index.js"; import { DUPLICATION_MODES } from "../duplication/index.js"; import { computeHighways } from "../highways/index.js"; import { computeHealth } from "../health/index.js"; import { computeLspSnapshot } from "../lsp/index.js"; import { CODEBASE_MAP_FORMATS, computeCodebaseMap } from "../map/index.js"; import { computeContentDrift } from "../drift/index.js"; import { computeOwnership } from "../ownership/index.js"; import { computeArchitectureRecommendations } from "../recommendations/index.js"; import { computeWorkspaces } from "../workspaces/index.js"; import type { BoundaryPreset, BoundariesConfig, CodebaseGraph } from "../types/index.js"; import { formatArchitectureRecommendationsText, formatBoundariesText, formatCodebaseMapText, formatChangesText, formatContentDriftText, formatClustersText, formatDeadExportsText, formatDependentsText, formatDuplicationText, formatFileContextText, formatForcesText, formatGroupsText, formatHealthText, formatHighwaysText, formatHotspotsText, formatLspSnapshotText, formatImpactText, formatModuleStructureText, formatOpportunitiesText, formatOwnershipText, formatOverviewText, formatProcessesText, formatRenameText, formatSearchText, formatSymbolContextText, formatWorkspacesText, } from "./formatters.js"; export const operationNames = [ "overview", "fileContext", "dependents", "hotspots", "moduleStructure", "forces", "deadExports", "opportunities", "duplication", "groups", "symbolContext", "search", "changes", "impact", "rename", "processes", "codebaseMap", "contentDrift", "health", "boundaries", "highways", "clusters", "ownership", "architectureRecommendations", "lspSnapshot", "workspaces", ] as const; export type OperationName = typeof operationNames[number]; export interface OperationContext { rootDir?: string; configPath?: string; } export interface Operation { name: OperationName; cliCommand: string; mcpTool: string; description: string; inputShape: z.ZodRawShape; inputSchema: z.ZodType; run: (graph: CodebaseGraph, input: TInput, context: OperationContext) => TResult; formatText: (result: TResult, input: TInput) => string; } export type OperationRunResult = | { ok: true; data: TResult } | { ok: false; error: string; data?: TResult }; const overviewInputShape = { depth: z.number().int().positive().optional().describe("Module depth (default: 1)"), } satisfies z.ZodRawShape; const overviewInputSchema = z.object(overviewInputShape).strict(); const fileContextInputShape = { filePath: z.string().min(1).describe("Relative path to the file"), } satisfies z.ZodRawShape; const fileContextInputSchema = z.object(fileContextInputShape).strict(); const dependentsInputShape = { filePath: z.string().min(1).describe("Relative path to the file"), depth: z.number().int().positive().optional().describe("Max traversal depth (default: 2)"), } satisfies z.ZodRawShape; const dependentsInputSchema = z.object(dependentsInputShape).strict(); const hotspotsInputShape = { metric: z.enum(HOTSPOT_METRICS).describe("Metric to rank by"), limit: z.number().int().positive().optional().describe("Number of results (default: 10)"), } satisfies z.ZodRawShape; const hotspotsInputSchema = z.object(hotspotsInputShape).strict(); const moduleStructureInputShape = { depth: z.number().int().positive().optional().describe("Module depth (default: 2)"), } satisfies z.ZodRawShape; const moduleStructureInputSchema = z.object(moduleStructureInputShape).strict(); const forcesInputShape = { cohesionThreshold: z.number().optional().describe("Min cohesion to be 'COHESIVE' (default: 0.6)"), tensionThreshold: z.number().optional().describe("Min tension to flag (default: 0.3)"), escapeThreshold: z.number().optional().describe("Min escape velocity to flag (default: 0.5)"), } satisfies z.ZodRawShape; const forcesInputSchema = z.object(forcesInputShape).strict(); const deadExportsInputShape = { module: z.string().min(1).optional().describe("Filter by module path (default: all modules)"), limit: z.number().int().positive().optional().describe("Max results (default: 20)"), } satisfies z.ZodRawShape; const deadExportsInputSchema = z.object(deadExportsInputShape).strict(); const opportunitiesInputShape = { limit: z.number().int().positive().optional().describe("Max opportunities (default: 20)"), } satisfies z.ZodRawShape; const opportunitiesInputSchema = z.object(opportunitiesInputShape).strict(); const duplicationInputShape = { mode: z.enum(DUPLICATION_MODES).optional().describe("Clone mode: strict, mild, or weak (default: mild)"), minTokens: z.number().int().positive().optional().describe("Minimum function body tokens to consider (default: 30)"), skipLocal: z.boolean().optional().describe("Ignore duplicate families confined to one file"), trace: z.string().min(1).optional().describe("Return token evidence for a duplicate family id"), } satisfies z.ZodRawShape; const duplicationInputSchema = z.object(duplicationInputShape).strict(); const emptyInputShape = {} satisfies z.ZodRawShape; const emptyInputSchema = z.object(emptyInputShape).strict(); const symbolContextInputShape = { name: z.string().min(1).describe("Symbol name (e.g., 'AuthService', 'getUserById')"), } satisfies z.ZodRawShape; const symbolContextInputSchema = z.object(symbolContextInputShape).strict(); const searchInputShape = { query: z.string().min(1).describe("Search query (supports camelCase, snake_case splitting)"), limit: z.number().int().positive().optional().describe("Max results (default: 20)"), } satisfies z.ZodRawShape; const searchInputSchema = z.object(searchInputShape).strict(); const changesInputShape = { scope: z.enum(CHANGE_SCOPES).optional().describe("Git diff scope (default: all)"), } satisfies z.ZodRawShape; const changesInputSchema = z.object(changesInputShape).strict(); const impactInputShape = { symbol: z.string().min(1).describe("Symbol name or qualified name (e.g., 'getUserById' or 'UserService.getUserById')"), } satisfies z.ZodRawShape; const impactInputSchema = z.object(impactInputShape).strict(); const renameInputShape = { oldName: z.string().min(1).describe("Current symbol name"), newName: z.string().min(1).describe("New symbol name"), dryRun: z.boolean().optional().describe("If true, only report references without renaming (default: true)"), } satisfies z.ZodRawShape; const renameInputSchema = z.object(renameInputShape).strict(); const processesInputShape = { entryPoint: z.string().min(1).optional().describe("Filter by entry point symbol name"), limit: z.number().int().positive().optional().describe("Max processes to return (default: all)"), } satisfies z.ZodRawShape; const processesInputSchema = z.object(processesInputShape).strict(); const codebaseMapInputShape = { focus: z.string().min(1).optional().describe("Symbol, file, or scope to focus the map on"), scope: z.string().min(1).optional().describe("Directory/module scope to include"), depth: z.number().int().positive().optional().describe("Graph traversal depth (default: 1)"), format: z.enum(CODEBASE_MAP_FORMATS).optional().describe("Export format: json, markdown, dot, or graphml"), contextBudget: z.number().int().positive().optional().describe("Approximate token budget for the context pack (default: 1200)"), } satisfies z.ZodRawShape; const codebaseMapInputSchema = z.object(codebaseMapInputShape).strict(); const contentDriftInputShape = { focus: z.string().min(1).optional().describe("File, scope, or symbol text to focus drift findings on"), scope: z.string().min(1).optional().describe("Directory/module scope to include"), minScore: z.number().min(0).max(100).optional().describe("Minimum drift score to report (default: 35)"), } satisfies z.ZodRawShape; const contentDriftInputSchema = z.object(contentDriftInputShape).strict(); const healthInputShape = { minScore: z.number().min(0).max(100).optional().describe("Minimum health score before the result fails (default: 70)"), score: z.boolean().optional().describe("Request compact score output on the CLI"), } satisfies z.ZodRawShape; const healthInputSchema = z.object(healthInputShape).strict(); const boundaryPresets = ["bulletproof", "layered", "hexagonal", "feature-sliced"] as const satisfies readonly BoundaryPreset[]; const boundariesInputShape = { preset: z.enum(boundaryPresets).optional().describe("Boundary preset to use when config has no boundaries"), list: z.boolean().optional().describe("List resolved zones and rules"), } satisfies z.ZodRawShape; const boundariesInputSchema = z.object(boundariesInputShape).strict(); const highwaysInputShape = { operation: z.string().min(1).optional().describe("Operation verb to focus on, such as create, update, or validate"), shape: z.string().min(1).optional().describe("Type/DTO shape to focus on"), minRoutes: z.number().int().positive().optional().describe("Minimum routes reaching a sink before reporting (default: 2)"), propose: z.boolean().optional().describe("Include reroute proposal metadata (default: false)"), trace: z.string().min(1).optional().describe("Return route evidence for one highway opportunity id"), } satisfies z.ZodRawShape; const highwaysInputSchema = z.object(highwaysInputShape).strict(); const clustersInputShape = { minFiles: z.number().int().positive().optional().describe("Filter clusters with at least N files (default: 0)"), } satisfies z.ZodRawShape; const clustersInputSchema = z.object(clustersInputShape).strict(); const ownershipInputShape = { groupBy: z.enum(["owner", "package", "directory"]).optional().describe("Group by owner, package, or directory"), effort: z.number().optional().describe("Minimum risk/effort score to include"), } satisfies z.ZodRawShape; const ownershipInputSchema = z.object(ownershipInputShape).strict(); const workspacesInputShape = { base: z.string().min(1).optional().describe("Base git ref for changed workspace detection"), changedOnly: z.boolean().optional().describe("Return only workspaces changed since base"), } satisfies z.ZodRawShape; const workspacesInputSchema = z.object(workspacesInputShape).strict(); type OverviewInput = z.infer; type FileContextInput = z.infer; type DependentsInput = z.infer; type HotspotsInput = z.infer; type ModuleStructureInput = z.infer; type ForcesInput = z.infer; type DeadExportsInput = z.infer; type OpportunitiesInput = z.infer; type DuplicationInput = z.infer; type EmptyInput = z.infer; type SymbolContextInput = z.infer; type SearchInput = z.infer; type ChangesInput = z.infer; type ImpactInput = z.infer; type RenameInput = z.infer; type ProcessesInput = z.infer; export type CodebaseMapInput = z.infer; type ContentDriftInput = z.infer; type HealthInput = z.infer; type BoundariesInput = z.infer; type HighwaysInput = z.infer; type ClustersInput = z.infer; type OwnershipInput = z.infer; type WorkspacesInput = z.infer; function loadBoundariesConfig(context: OperationContext): BoundariesConfig | undefined { if (!context.rootDir && !context.configPath) return undefined; return loadConfig(context.rootDir ?? process.cwd(), { configPath: context.configPath }).config.boundaries; } export const operations = { overview: { name: "overview", cliCommand: "overview", mcpTool: "codebase_overview", description: "Get a high-level overview of the codebase: total files, modules, top-depended files, and key metrics. Use when: first exploring a codebase, 'what does this project look like'. Not for: module details (use get_module_structure) or data flow (use analyze_forces)", inputShape: overviewInputShape, inputSchema: overviewInputSchema, run: (graph: CodebaseGraph, _input: OverviewInput) => computeOverview(graph), formatText: formatOverviewText, } satisfies Operation>, fileContext: { name: "fileContext", cliCommand: "file", mcpTool: "file_context", description: "Get detailed context for a specific file: exports, imports, dependents, and all metrics. Use when: 'tell me about this file', understanding a file before modifying it. Not for: symbol-level detail (use symbol_context)", inputShape: fileContextInputShape, inputSchema: fileContextInputSchema, run: (graph: CodebaseGraph, input: FileContextInput) => computeFileContext(graph, input.filePath), formatText: formatFileContextText, } satisfies Operation>, dependents: { name: "dependents", cliCommand: "dependents", mcpTool: "get_dependents", description: "Get all files that import a given file, with transitive dependents. File-level blast radius. Use when: 'what breaks if I change this file'. Not for: symbol-level impact (use impact_analysis)", inputShape: dependentsInputShape, inputSchema: dependentsInputSchema, run: (graph: CodebaseGraph, input: DependentsInput) => computeDependents(graph, input.filePath, input.depth), formatText: formatDependentsText, } satisfies Operation>, hotspots: { name: "hotspots", cliCommand: "hotspots", mcpTool: "find_hotspots", description: "Rank files by any metric: coupling, pagerank, fan_in, fan_out, betweenness, tension, escape_velocity, churn, complexity, blast_radius, coverage. Use when: 'what are the riskiest files', 'which files need tests', 'most complex files'. Not for: module-level analysis (use get_module_structure)", inputShape: hotspotsInputShape, inputSchema: hotspotsInputSchema, run: (graph: CodebaseGraph, input: HotspotsInput) => computeHotspots(graph, input.metric, input.limit), formatText: formatHotspotsText, } satisfies Operation>, moduleStructure: { name: "moduleStructure", cliCommand: "modules", mcpTool: "get_module_structure", description: "Get module/directory structure with cross-module dependencies, cohesion scores, and circular deps. Use when: 'how are modules organized', 'what depends on what module'. Not for: emergent clusters (use get_clusters) or file-level metrics (use find_hotspots)", inputShape: moduleStructureInputShape, inputSchema: moduleStructureInputSchema, run: (graph: CodebaseGraph, _input: ModuleStructureInput) => computeModuleStructure(graph), formatText: formatModuleStructureText, } satisfies Operation>, forces: { name: "forces", cliCommand: "forces", mcpTool: "analyze_forces", description: "Analyze module health: find misplaced files (tension), bridge files connecting otherwise-disconnected modules, and extraction candidates. Use when: 'what is architecturally wrong', 'which modules are coupled', 'what files should be moved'. Not for: file-level metrics (use find_hotspots)", inputShape: forcesInputShape, inputSchema: forcesInputSchema, run: (graph: CodebaseGraph, input: ForcesInput) => computeForces(graph, input.cohesionThreshold, input.tensionThreshold, input.escapeThreshold), formatText: formatForcesText, } satisfies Operation>, deadExports: { name: "deadExports", cliCommand: "dead-exports", mcpTool: "find_dead_exports", description: "Find unused exports across the codebase - exports that no other file imports. Use when: cleaning up dead code, reducing API surface. Not for: finding used exports (use file_context)", inputShape: deadExportsInputShape, inputSchema: deadExportsInputSchema, run: (graph: CodebaseGraph, input: DeadExportsInput) => computeDeadExports(graph, input.module, input.limit), formatText: formatDeadExportsText, } satisfies Operation>, opportunities: { name: "opportunities", cliCommand: "opportunities", mcpTool: "find_opportunities", description: "Rank code quality and refactoring opportunities with evidence, confidence, and suggested follow-up commands. Use when: 'what should I improve', 'find refactoring opportunities', 'what needs tests'. Not for: raw metrics only (use find_hotspots or analyze_forces)", inputShape: opportunitiesInputShape, inputSchema: opportunitiesInputSchema, run: (graph: CodebaseGraph, input: OpportunitiesInput) => computeOpportunities(graph, input.limit), formatText: formatOpportunitiesText, } satisfies Operation>, duplication: { name: "duplication", cliCommand: "duplicates", mcpTool: "find_duplicates", description: "Detect duplicate function families with strict, mild, or weak clone modes. Use when: finding copy-paste logic, drift between similar functions, or refactor candidates. Not for: unused code (use find_dead_exports) or module-level cohesion (use analyze_forces)", inputShape: duplicationInputShape, inputSchema: duplicationInputSchema, run: (graph: CodebaseGraph, input: DuplicationInput) => computeDuplication(graph, input), formatText: formatDuplicationText, } satisfies Operation>, groups: { name: "groups", cliCommand: "groups", mcpTool: "get_groups", description: "Get top-level directory groups with aggregate metrics: files, LOC, importance (PageRank), coupling. Use when: 'what are the main areas of this codebase', high-level grouping overview. Not for: detailed module metrics (use get_module_structure)", inputShape: emptyInputShape, inputSchema: emptyInputSchema, run: (graph: CodebaseGraph, _input: EmptyInput) => computeGroups(graph), formatText: formatGroupsText, } satisfies Operation>, symbolContext: { name: "symbolContext", cliCommand: "symbol", mcpTool: "symbol_context", description: "Find all callers and callees of a function, class, or method with importance metrics. Use when: 'who calls X', 'trace this function', 'what depends on this symbol'. Not for: text search (use search) or file-level dependencies (use get_dependents)", inputShape: symbolContextInputShape, inputSchema: symbolContextInputSchema, run: (graph: CodebaseGraph, input: SymbolContextInput) => computeSymbolContext(graph, input.name), formatText: formatSymbolContextText, } satisfies Operation>, search: { name: "search", cliCommand: "search", mcpTool: "search", description: "Search files and symbols by keyword. Returns ranked results with symbol locations. Use when: 'find files related to auth', 'where is getUserById defined'. Not for: structured call graph queries (use symbol_context)", inputShape: searchInputShape, inputSchema: searchInputSchema, run: (graph: CodebaseGraph, input: SearchInput) => computeSearch(graph, input.query, input.limit), formatText: formatSearchText, } satisfies Operation>, changes: { name: "changes", cliCommand: "changes", mcpTool: "detect_changes", description: "Detect changed files from git diff with risk metrics per file. Use when: starting a review, triaging changes, 'what changed'. Not for: symbol-level impact (use impact_analysis)", inputShape: changesInputShape, inputSchema: changesInputSchema, run: (graph: CodebaseGraph, input: ChangesInput, context: OperationContext) => computeChanges(graph, input.scope, context.rootDir), formatText: formatChangesText, } satisfies Operation>, impact: { name: "impact", cliCommand: "impact", mcpTool: "impact_analysis", description: "Analyze blast radius of changing a specific function or class. Symbol-level, depth-grouped, with risk labels (WILL BREAK / LIKELY / MAY NEED TESTING). Use when: 'what breaks if I change getUserById'. Not for: file-level dependencies (use get_dependents)", inputShape: impactInputShape, inputSchema: impactInputSchema, run: (graph: CodebaseGraph, input: ImpactInput) => impactAnalysis(graph, input.symbol), formatText: formatImpactText, } satisfies Operation>, rename: { name: "rename", cliCommand: "rename", mcpTool: "rename_symbol", description: "Read-only: find all reference locations for a symbol across the codebase, with confidence levels. Does not modify files. Use when: planning a rename, finding all usages. Not for: call graph analysis (use symbol_context)", inputShape: renameInputShape, inputSchema: renameInputSchema, run: (graph: CodebaseGraph, input: RenameInput) => renameSymbol(graph, input.oldName, input.newName, input.dryRun ?? true), formatText: formatRenameText, } satisfies Operation>, processes: { name: "processes", cliCommand: "processes", mcpTool: "get_processes", description: "Trace execution flows from entry points through the call graph. Returns step-by-step paths showing how requests flow through the codebase. Use when: 'how does this app start', 'trace request flow', 'what are the entry points'. Not for: static file dependencies (use get_dependents)", inputShape: processesInputShape, inputSchema: processesInputSchema, run: (graph: CodebaseGraph, input: ProcessesInput) => computeProcesses(graph, input.entryPoint, input.limit), formatText: formatProcessesText, } satisfies Operation>, codebaseMap: { name: "codebaseMap", cliCommand: "map", mcpTool: "get_codebase_map", description: "Build a deterministic focused graph plus a token-bounded context pack for AI agents. Use when: preparing a code context bundle, visualizing scope/symbol neighborhoods, or giving an LLM the smallest useful map. Not for: raw execution traces (use get_processes) or route convergence analysis (use analyze_highways)", inputShape: codebaseMapInputShape, inputSchema: codebaseMapInputSchema, run: (graph: CodebaseGraph, input: CodebaseMapInput) => computeCodebaseMap(graph, input), formatText: formatCodebaseMapText, } satisfies Operation>, contentDrift: { name: "contentDrift", cliCommand: "drift", mcpTool: "detect_content_drift", description: "Detect deterministic file, folder, side-effect, shape, and test placement drift. Use when: checking whether names and scopes still match behavior before refactors or CI baselining. Not for: enforcing CI gates without a baseline (use check or future ci wrapper)", inputShape: contentDriftInputShape, inputSchema: contentDriftInputSchema, run: (graph: CodebaseGraph, input: ContentDriftInput) => computeContentDrift(graph, input), formatText: formatContentDriftText, } satisfies Operation>, health: { name: "health", cliCommand: "health", mcpTool: "get_health_score", description: "Compute a CI-gateable codebase health score with per-file maintainability, CRAP, coverage reachability, and risk hotspots. Use when: gating PR quality, finding files that combine complexity/churn/coupling/size, or tracking maintainability over time. Not for: route discipline (use analyze_highways) or naming drift (use detect_content_drift)", inputShape: healthInputShape, inputSchema: healthInputSchema, run: (graph: CodebaseGraph, input: HealthInput, context) => computeHealth(graph, input, context), formatText: formatHealthText, } satisfies Operation>, boundaries: { name: "boundaries", cliCommand: "boundaries", mcpTool: "check_boundaries", description: "Evaluate architecture boundary zones against import edges. Supports presets, custom zones, allow/forbid rules, and a list view. Use when: enforcing layering, ports/adapters, or feature-sliced import direction. Not for: circular dependencies (use check)", inputShape: boundariesInputShape, inputSchema: boundariesInputSchema, run: (graph: CodebaseGraph, input: BoundariesInput, context) => computeBoundaries(graph, { preset: input.preset, list: input.list, config: loadBoundariesConfig(context) }), formatText: formatBoundariesText, } satisfies Operation>, highways: { name: "highways", cliCommand: "highways", mcpTool: "analyze_highways", description: "Detect repeated entry-to-sink routes that should converge on one canonical operation path. Finds bypass and cowpath routes with route chains, blast radius, evidence, and a safe reroute context pack. Use when: enforcing dataflow discipline, finding ad-hoc routes, or planning canonical shared paths. Not for: generic process traces (use get_processes)", inputShape: highwaysInputShape, inputSchema: highwaysInputSchema, run: (graph: CodebaseGraph, input: HighwaysInput) => computeHighways(graph, input), formatText: formatHighwaysText, } satisfies Operation>, clusters: { name: "clusters", cliCommand: "clusters", mcpTool: "get_clusters", description: "Get community-detected clusters of related files using Louvain algorithm. Discovers emergent groupings that may differ from directory structure. Use when: 'what files are related', 'find natural groupings', 'which files change together'. Not for: directory-based modules (use get_module_structure)", inputShape: clustersInputShape, inputSchema: clustersInputSchema, run: (graph: CodebaseGraph, input: ClustersInput) => computeClusters(graph, input.minFiles), formatText: formatClustersText, } satisfies Operation>, ownership: { name: "ownership", cliCommand: "owners", mcpTool: "get_ownership", description: "Group files by CODEOWNERS/git ownership, package, or directory with bus-factor and risk signals. Use when: finding owner concentration, orphaned critical paths, or handoff risk.", inputShape: ownershipInputShape, inputSchema: ownershipInputSchema, run: (graph: CodebaseGraph, input: OwnershipInput, context) => computeOwnership(graph, context.rootDir ?? process.cwd(), input), formatText: formatOwnershipText, } satisfies Operation>, architectureRecommendations: { name: "architectureRecommendations", cliCommand: "architecture", mcpTool: "get_architecture_recommendations", description: "Rank extraction, seam, tension, and locality recommendations with effort, evidence, affected files, and context commands. Use when: planning architecture cleanup from graph evidence.", inputShape: emptyInputShape, inputSchema: emptyInputSchema, run: (graph: CodebaseGraph, _input: EmptyInput) => computeArchitectureRecommendations(graph), formatText: formatArchitectureRecommendationsText, } satisfies Operation>, lspSnapshot: { name: "lspSnapshot", cliCommand: "lsp", mcpTool: "get_lsp_snapshot", description: "Return advisory editor diagnostics and hover facts derived from the same graph as batch analysis. Use when: comparing editor diagnostics with CLI output.", inputShape: emptyInputShape, inputSchema: emptyInputSchema, run: (graph: CodebaseGraph, _input: EmptyInput) => computeLspSnapshot(graph), formatText: formatLspSnapshotText, } satisfies Operation>, workspaces: { name: "workspaces", cliCommand: "workspaces", mcpTool: "get_workspaces", description: "Detect package/workspace scopes, changed workspaces, and cross-package circular dependency evidence. Use when: scoping CI to changed packages in a monorepo.", inputShape: workspacesInputShape, inputSchema: workspacesInputSchema, run: (graph: CodebaseGraph, input: WorkspacesInput, context) => computeWorkspaces(graph, context.rootDir ?? process.cwd(), input), formatText: formatWorkspacesText, } satisfies Operation>, } as const; export type RegisteredOperation = typeof operations[OperationName]; export type OperationCliCommand = RegisteredOperation["cliCommand"]; export type OperationMcpTool = RegisteredOperation["mcpTool"]; export const operationList: readonly RegisteredOperation[] = operationNames.map((name) => operations[name]); function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } function errorMessageForData(data: unknown): string | undefined { if (!isRecord(data)) return undefined; if (typeof data.error === "string") return data.error; if (data.notFound === true && typeof data.symbol === "string") return `Symbol not found: ${data.symbol}`; if (data.notFound === true) return "Result not found"; return undefined; } function validationErrorMessage(error: z.ZodError): string { return error.issues .map((issue) => { const issuePath = issue.path.join("."); return issuePath ? `${issuePath}: ${issue.message}` : issue.message; }) .join("; "); } export function getOperation(name: OperationName): RegisteredOperation { return operations[name]; } export function getOperationByCliCommand(command: string): RegisteredOperation | undefined { return operationList.find((operation) => operation.cliCommand === command); } export function getOperationByMcpTool(toolName: string): RegisteredOperation | undefined { return operationList.find((operation) => operation.mcpTool === toolName); } export function parseOperationInput( operation: Operation, input: unknown, ): OperationRunResult { const parsed = operation.inputSchema.safeParse(input); if (!parsed.success) { return { ok: false, error: validationErrorMessage(parsed.error) }; } return { ok: true, data: parsed.data }; } export function runOperation( operation: Operation, graph: CodebaseGraph, input: TInput, context: OperationContext = {}, ): OperationRunResult { try { const data = operation.run(graph, input, context); const error = errorMessageForData(data); if (error) return { ok: false, error, data }; return { ok: true, data }; } catch (err) { const error = err instanceof Error ? err.message : String(err); return { ok: false, error }; } }