All files write.ts

80% Statements 300/375
67.3% Branches 70/104
87.5% Functions 7/8
80% Lines 300/375

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642                  1x 1x 1x                                 1x                   1x 1x       1x   1x 1x 1x     1x   1x       1x                                   1x 1x               1x                                                     1x 1x 1x                                                                                                       1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x       11x     11x       11x         11x 3x 3x     11x 1x 1x 1x 1x 1x 1x       11x                           11x 5x 5x 5x 5x 5x 5x     11x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x     11x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x     1x 1x 11x 11x 11x                                                   1x 13x   13x 13x     13x 13x   13x 5x 5x 5x 5x 5x     5x     13x 13x 5x 5x 5x     13x     13x   13x 13x 1x 1x 1x 1x 1x 13x                 1x 5x 5x 1x 1x   4x 4x 4x     4x 5x 5x 5x 5x 5x 5x 5x   1x       1x 1x 1x 1x   5x   1x 1x 1x 1x 1x 1x     1x 1x   5x   1x 1x 1x 1x 1x 1x     1x 1x   5x                       5x   3x   3x 5x 1x 1x 1x 1x 1x 5x                         1x 23x     23x 23x           13x 13x 13x 13x 13x   13x   13x 13x 13x 13x 13x 13x   6x 6x 6x 6x 6x 6x 6x   13x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   13x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   13x   2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   13x   2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x   13x   1x 1x 1x     1x     1x     1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x   13x         13x                 13x 13x                 1x 8x 8x 8x 8x   8x 8x 8x 8x 8x 8x 8x 8x   3x 3x 3x   8x   2x 2x 2x 2x 1x 1x 1x 1x 1x   8x   2x 2x 2x 2x 1x 1x 1x 1x 1x   8x                     8x       8x   8x 8x 1x 1x 8x  
/**
 * MCP Config Writer Module
 *
 * Writes SnapBack MCP configuration to AI client config files.
 * Handles backup creation, merging with existing config, and various formats.
 *
 * @packageDocumentation
 */
 
import { execSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname } from "node:path";
 
import type {
	AIClientConfig,
	AIClientFormat,
	MCPConfig,
	MCPServerConfig,
	RemoveResult,
	SnapbackConfigOptions,
	WriteResult,
} from "./types.js";
 
// =============================================================================
// PATH RESOLUTION UTILITIES
// =============================================================================
 
/** Cached node path to avoid repeated lookups */
let cachedNodePath: string | null = null;
 
/**
 * Resolve the absolute path to the Node.js executable
 *
 * This is critical for MCP reliability - using just "node" depends on PATH
 * which varies between environments (terminal vs IDE vs system service).
 *
 * @returns Absolute path to node, or "node" as fallback
 */
export function resolveNodePath(): string {
	if (cachedNodePath) {
		return cachedNodePath;
	}
 
	try {
		// Try `which node` (Unix) or `where node` (Windows)
		const isWindows = process.platform === "win32";
		const command = isWindows ? "where node" : "which node";
		const result = execSync(command, { encoding: "utf-8", timeout: 5000 }).trim();
 
		// On Windows, `where` may return multiple paths - take the first
		const nodePath = result.split(/\r?\n/)[0].trim();
 
		if (nodePath && existsSync(nodePath)) {
			cachedNodePath = nodePath;
			return nodePath;
		}
	} catch {
		// Fallback: try common paths
		const commonPaths = [
			"/opt/homebrew/bin/node", // macOS ARM (Homebrew)
			"/usr/local/bin/node", // macOS Intel (Homebrew)
			"/usr/bin/node", // Linux
			"C:\\Program Files\\nodejs\\node.exe", // Windows
		];
 
		for (const path of commonPaths) {
			if (existsSync(path)) {
				cachedNodePath = path;
				return path;
			}
		}
	}
 
	// Final fallback - use "node" and hope PATH is set
	return "node";
}
 
/**
 * Check if a command is executable (exists in PATH or is absolute path)
 *
 * @param command - Command to check
 * @returns True if command is likely executable
 */
export function isCommandExecutable(command: string): boolean {
	// If it's an absolute path, check if file exists
	if (command.startsWith("/") || command.match(/^[A-Z]:\\/i)) {
		return existsSync(command);
	}
 
	// For relative commands, try to find them
	try {
		const isWindows = process.platform === "win32";
		const cmd = isWindows ? `where ${command}` : `which ${command}`;
		execSync(cmd, { encoding: "utf-8", timeout: 5000 });
		return true;
	} catch {
		return false;
	}
}
 
// =============================================================================
// CONFIG GENERATION
// =============================================================================
 
/**
 * Clients that ONLY support stdio transport (no HTTP/SSE)
 * These clients require command + args, not url
 *
 * @see https://modelcontextprotocol.io/docs/develop/connect-local-servers
 */
const STDIO_ONLY_CLIENTS: Set<string> = new Set([
	"claude", // Claude Desktop only supports stdio transport
]);
 
/**
 * Generate SnapBack MCP server configuration
 *
 * @param options - Configuration options
 * @returns MCP server config for SnapBack
 *
 * @example
 * ```ts
 * // RECOMMENDED: NPX mode for npm-installed CLI
 * // Best for users who installed via: npm install -g @snapback/cli
 * const npxConfig = getSnapbackMCPConfig({
 *   useNpx: true,
 *   workspaceRoot: '/path/to/project'
 * });
 * // Generates: npx @snapback/cli mcp --stdio --workspace /path/to/project
 *
 * // Workspace ID auth (no API key in config)
 * const config = getSnapbackMCPConfig({
 *   workspaceId: 'ws_a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6'
 * });
 *
 * // Legacy: API key auth (still supported)
 * const legacyConfig = getSnapbackMCPConfig({ apiKey: 'sb_live_xxx' });
 *
 * // Local development mode
 * const devConfig = getSnapbackMCPConfig({
 *   useLocalDev: true,
 *   localCliPath: '/path/to/apps/cli/dist/index.js',
 *   workspaceRoot: '/path/to/project'
 * });
 *
 * // Custom remote server
 * const customConfig = getSnapbackMCPConfig({
 *   serverUrl: 'https://custom-mcp.example.com',
 *   workspaceId: 'ws_xxx'
 * });
 *
 * // Legacy stdio mode (using binary)
 * const stdioConfig = getSnapbackMCPConfig({
 *   useBinary: true,
 *   apiKey: 'sb_live_xxx'
 * });
 *
 * // Claude Desktop (auto-uses npx since Claude Desktop requires stdio)
 * const claudeConfig = getSnapbackMCPConfig({
 *   client: 'claude',
 *   workspaceRoot: '/path/to/project'
 * });
 * ```
 */
export function getSnapbackMCPConfig(options: SnapbackConfigOptions = {}): MCPServerConfig {
	const {
		apiKey,
		workspaceId,
		serverUrl,
		useBinary = false,
		customCommand,
		additionalEnv,
		workspaceRoot,
		useLocalDev = false,
		localCliPath,
		client,
	} = options;
 
	// Auto-enable npx mode for stdio-only clients (like Claude Desktop)
	// These clients don't support HTTP transport, so we MUST use stdio
	const useNpx = options.useNpx ?? (client ? STDIO_ONLY_CLIENTS.has(client) : false);
 
	// Build environment variables
	const env: Record<string, string> = { ...additionalEnv };
 
	// Workspace ID is preferred over API key for MCP authentication
	// When workspaceId is set, tier is resolved server-side via workspace_links table
	if (workspaceId) {
		env.SNAPBACK_WORKSPACE_ID = workspaceId;
	}
 
	// API key can still be provided for backwards compatibility or direct auth
	if (apiKey) {
		env.SNAPBACK_API_KEY = apiKey;
	}
 
	// Determine command
	if (customCommand) {
		return {
			command: customCommand,
			args: [],
			...(Object.keys(env).length > 0 && { env }),
		};
	}
 
	// Priority 1: NPX mode - for npm-installed CLI (recommended for npm users)
	// Command: npx @snapback/cli mcp --stdio --workspace <path>
	if (useNpx) {
		const tier = apiKey ? "pro" : "free";
		const args = ["@snapback/cli", "mcp", "--stdio", "--tier", tier];
		if (workspaceRoot) {
			args.push("--workspace", workspaceRoot);
		}
		return {
			command: "npx",
			args,
			...(Object.keys(env).length > 0 && { env }),
		};
	}
 
	// Priority 2: Remote HTTP server (Fly.io) - DEFAULT for non-explicit modes
	if (serverUrl || (!useLocalDev && !useBinary)) {
		const url = serverUrl || "https://api.snapback.dev";
		return {
			url,
			...(Object.keys(env).length > 0 && { env }),
		};
	}
 
	// Priority 2: Local development mode - direct node execution with workspace
	if (useLocalDev && localCliPath) {
		const tier = apiKey ? "pro" : "free";
		const args = [localCliPath, "mcp", "--stdio", "--tier", tier];
		if (workspaceRoot) {
			args.push("--workspace", workspaceRoot);
		}
		// CRITICAL: Use absolute path to node to avoid PATH resolution issues
		// IDE environments often have different PATH than terminal
		const nodePath = resolveNodePath();
		return {
			command: nodePath,
			args,
			...(Object.keys(env).length > 0 && { env }),
		};
	}
 
	// Priority 3: Binary mode (legacy stdio transport)
	if (useBinary) {
		const tier = apiKey ? "pro" : "free";
		const args = ["mcp", "--stdio", "--tier", tier];
		if (workspaceRoot) {
			args.push("--workspace", workspaceRoot);
		}
		return {
			command: "snapback",
			args,
			...(Object.keys(env).length > 0 && { env }),
		};
	}
 
	// Fallback: Should not reach here due to Priority 1, but kept for safety
	return {
		url: "https://api.snapback.dev",
		...(Object.keys(env).length > 0 && { env }),
	};
}
 
// =============================================================================
// CONFIG WRITING
// =============================================================================
 
/**
 * Write SnapBack MCP config to an AI client's config file
 *
 * @param client - The AI client to configure
 * @param mcpConfig - The MCP server configuration
 * @returns Result of the write operation
 *
 * @example
 * ```ts
 * const client = getClient('cursor');
 * const mcpConfig = getSnapbackMCPConfig({ apiKey: 'sk_...' });
 *
 * const result = writeClientConfig(client, mcpConfig);
 * if (result.success) {
 *   console.log('Configured! Backup at:', result.backup);
 * } else {
 *   console.error('Failed:', result.error);
 * }
 * ```
 */
export function writeClientConfig(client: AIClientConfig, mcpConfig: MCPServerConfig): WriteResult {
	try {
		// Ensure directory exists
		const configDir = dirname(client.configPath);
		mkdirSync(configDir, { recursive: true });
 
		// Read existing config or start fresh
		let existingConfig: MCPConfig = { mcpServers: {} };
		let hasExistingConfig = false;
 
		if (existsSync(client.configPath)) {
			try {
				const content = readFileSync(client.configPath, "utf-8");
				existingConfig = JSON.parse(content) as MCPConfig;
				hasExistingConfig = Object.keys(existingConfig).length > 0;
			} catch {
				// Invalid JSON, will overwrite
			}
		}
 
		// Create backup if there's existing content
		let backup: string | undefined;
		if (hasExistingConfig) {
			backup = `${client.configPath}.backup.${Date.now()}`;
			writeFileSync(backup, JSON.stringify(existingConfig, null, 2));
		}
 
		// Merge configs based on format
		const newConfig = mergeConfig(existingConfig, mcpConfig, client.format);
 
		// Write updated config
		writeFileSync(client.configPath, JSON.stringify(newConfig, null, 2));
 
		return { success: true, backup };
	} catch (error) {
		return {
			success: false,
			error: error instanceof Error ? error.message : "Unknown error",
		};
	}
}
 
/**
 * Remove SnapBack configuration from an AI client
 * §10.1: Removes namespaced entries (snapback-<client>)
 *
 * @param client - The AI client to remove config from
 * @returns Result of the removal operation
 */
export function removeSnapbackConfig(client: AIClientConfig): RemoveResult {
	try {
		if (!existsSync(client.configPath)) {
			return { success: true }; // Nothing to remove
		}
 
		const content = readFileSync(client.configPath, "utf-8");
		const config = JSON.parse(content) as MCPConfig;
		const serverKey = getServerKey(client.format);
 
		// Remove based on format
		switch (client.format) {
			case "claude":
			case "cursor":
			case "windsurf":
			case "cline":
			case "roo-code":
			case "gemini":
			case "qoder":
				// Remove namespaced key
				if (config.mcpServers?.[serverKey]) {
					delete config.mcpServers[serverKey];
				}
				// Also remove legacy "snapback" key if present
				if (config.mcpServers?.snapback) {
					delete config.mcpServers.snapback;
				}
				break;
 
			case "vscode": {
				// VS Code uses "servers" not "mcpServers"
				const vscodeConfig = config as unknown as Record<string, unknown>;
				const servers = vscodeConfig.servers as Record<string, unknown> | undefined;
				if (servers?.[serverKey]) {
					delete servers[serverKey];
				}
				if (servers?.snapback) {
					delete servers.snapback;
				}
				break;
			}
 
			case "zed": {
				// Zed uses "context_servers" not "mcpServers"
				const zedConfig = config as unknown as Record<string, unknown>;
				const contextServers = zedConfig.context_servers as Record<string, unknown> | undefined;
				if (contextServers?.[serverKey]) {
					delete contextServers[serverKey];
				}
				if (contextServers?.snapback) {
					delete contextServers.snapback;
				}
				break;
			}
 
			case "continue": {
				// Continue uses different structure
				const experimental = (config as unknown as Record<string, unknown>).experimental as
					| Record<string, unknown>
					| undefined;
				if (experimental?.modelContextProtocolServers) {
					const servers = experimental.modelContextProtocolServers as Array<{ name: string }>;
					// Remove all snapback entries (namespaced and legacy)
					experimental.modelContextProtocolServers = servers.filter((s) => !s.name.startsWith("snapback"));
				}
				break;
			}
		}
 
		writeFileSync(client.configPath, JSON.stringify(config, null, 2));
 
		return { success: true };
	} catch (error) {
		return {
			success: false,
			error: error instanceof Error ? error.message : "Unknown error",
		};
	}
}
 
// =============================================================================
// HELPER FUNCTIONS
// =============================================================================
 
/**
 * §10.1: Generate namespaced server key for client
 * SnapBack SHALL NEVER use just "snapback" - always "snapback-<client>"
 *
 * @param client - Client format (e.g., "claude", "cursor")
 * @returns Namespaced server key (e.g., "snapback-claude")
 */
export function getServerKey(client: AIClientFormat | undefined): string {
	if (!client) {
		return "snapback"; // Legacy fallback - should be avoided
	}
	return `snapback-${client}`;
}
 
/**
 * Merge SnapBack config into existing config based on format
 * §10.1: Uses namespaced server keys (snapback-<client>)
 */
function mergeConfig(
	existing: MCPConfig,
	snapbackConfig: MCPServerConfig,
	format: AIClientConfig["format"],
): MCPConfig | Record<string, unknown> {
	// §10.1: Use namespaced server key
	const serverKey = getServerKey(format);
 
	switch (format) {
		case "claude":
		case "cursor":
		case "cline":
		case "roo-code":
		case "gemini":
			// Standard mcpServers format with namespaced key
			return {
				...existing,
				mcpServers: {
					...(existing.mcpServers || {}),
					[serverKey]: snapbackConfig,
				},
			};
 
		case "windsurf":
			// Windsurf uses standard format but supports disabled and alwaysAllow fields for UX
			return {
				...existing,
				mcpServers: {
					...(existing.mcpServers || {}),
					[serverKey]: {
						...snapbackConfig,
						disabled: false, // Explicitly enable
						alwaysAllow: [], // Empty by default, user can configure
					},
				},
			};
 
		case "qoder":
			// Qoder requires explicit type field for transport
			return {
				...existing,
				mcpServers: {
					...(existing.mcpServers || {}),
					[serverKey]: {
						type: "stdio", // Required by Qoder
						...snapbackConfig,
					},
				},
			};
 
		case "vscode": {
			// VS Code uses "servers" not "mcpServers" and requires explicit type
			const vscodeConfig = existing as unknown as Record<string, unknown>;
			const servers = (vscodeConfig.servers || {}) as Record<string, unknown>;
			// Remove mcpServers if it exists (shouldn't be there for VS Code)
			const { mcpServers: _, ...rest } = vscodeConfig;
			return {
				...rest,
				servers: {
					...servers,
					[serverKey]: {
						type: "stdio", // Required by VS Code
						...snapbackConfig,
					},
				},
			};
		}
 
		case "zed": {
			// Zed uses "context_servers" not "mcpServers"
			const zedConfig = existing as unknown as Record<string, unknown>;
			const contextServers = (zedConfig.context_servers || {}) as Record<string, unknown>;
			// Remove mcpServers if it exists (shouldn't be there for Zed)
			const { mcpServers: _, ...rest } = zedConfig;
			return {
				...rest,
				context_servers: {
					...contextServers,
					[serverKey]: snapbackConfig,
				},
			};
		}
 
		case "continue": {
			// Continue uses experimental.modelContextProtocolServers array
			const continueConfig = existing as unknown as Record<string, unknown>;
			const experimental = (continueConfig.experimental || {}) as Record<string, unknown>;
			const servers = (experimental.modelContextProtocolServers || []) as Array<Record<string, unknown>>;
 
			// Remove existing snapback entries if present
			const filteredServers = servers.filter((s) => {
				const name = s.name as string;
				return !name?.startsWith("snapback");
			});
 
			// Add new snapback config with namespaced name
			filteredServers.push({
				name: serverKey,
				...snapbackConfig,
			});
 
			return {
				...continueConfig,
				experimental: {
					...experimental,
					modelContextProtocolServers: filteredServers,
				},
			};
		}
 
		case "aider":
			// Aider uses YAML - handled separately (this shouldn't be called)
			// For now, return existing config unchanged
			return existing;
 
		default:
			// Fallback to standard format with namespaced key
			return {
				...existing,
				mcpServers: {
					...(existing.mcpServers || {}),
					[serverKey]: snapbackConfig,
				},
			};
	}
}
 
/**
 * Validate that a config was written correctly
 * §10.1: Checks for namespaced server keys (snapback-<client>)
 *
 * @param client - Client to validate
 * @returns True if SnapBack is properly configured
 */
export function validateConfig(client: AIClientConfig): boolean {
	try {
		const content = readFileSync(client.configPath, "utf-8");
		const config = JSON.parse(content) as MCPConfig;
		const serverKey = getServerKey(client.format);
 
		switch (client.format) {
			case "claude":
			case "cursor":
			case "windsurf":
			case "cline":
			case "roo-code":
			case "gemini":
			case "qoder": {
				// Check namespaced key first, fall back to legacy "snapback" for backwards compat
				const serverConfig = config.mcpServers?.[serverKey] || config.mcpServers?.snapback;
				return Boolean(serverConfig?.command || serverConfig?.url);
			}
 
			case "vscode": {
				// VS Code uses "servers" not "mcpServers"
				const vscodeConfig = config as unknown as Record<string, unknown>;
				const servers = vscodeConfig.servers as Record<string, unknown> | undefined;
				const serverConfig = servers?.[serverKey] || servers?.snapback;
				if (typeof serverConfig === "object" && serverConfig !== null) {
					const cfg = serverConfig as { command?: string; url?: string };
					return Boolean(cfg.command || cfg.url);
				}
				return false;
			}
 
			case "zed": {
				// Zed uses "context_servers" not "mcpServers"
				const zedConfig = config as unknown as Record<string, unknown>;
				const contextServers = zedConfig.context_servers as Record<string, unknown> | undefined;
				const serverConfig = contextServers?.[serverKey] || contextServers?.snapback;
				if (typeof serverConfig === "object" && serverConfig !== null) {
					const cfg = serverConfig as { command?: string; url?: string };
					return Boolean(cfg.command || cfg.url);
				}
				return false;
			}
 
			case "continue": {
				const expCfg = (config as unknown as Record<string, unknown>).experimental as
					| Record<string, unknown>
					| undefined;
				const srvs = expCfg?.modelContextProtocolServers as
					| Array<{ name: string; command?: string; url?: string }>
					| undefined;
				// Check for any snapback entry (namespaced or legacy)
				return Boolean(srvs?.some((s) => s.name.startsWith("snapback") && (s.command || s.url)));
			}
 
			case "aider":
				// YAML validation would need a YAML parser
				return false;
 
			default:
				return false;
		}
	} catch {
		return false;
	}
}