From e3bc5f01439d0a0fe3283e9fcc1e9ec9aef8e0d8 Mon Sep 17 00:00:00 2001 From: Ara Date: Tue, 2 Sep 2025 16:14:55 -0700 Subject: [PATCH] Setup Raw Structure for implementing multi-workspace support with WorkspaceRoot (#5849) * Setup Raw Structure for implementing multi-workspace support with WorkspaceRoot * Remove Shortcut of Cline from its title --- .changeset/small-lions-train.md | 5 + src/core/controller/file/createRuleFile.ts | 4 +- src/core/controller/file/deleteRuleFile.ts | 4 +- .../file/ifFileExistsRelativePath.ts | 9 +- .../controller/file/openFileRelativePath.ts | 9 +- src/core/controller/file/toggleClineRule.ts | 11 +- .../controller/task/deleteAllTaskHistory.ts | 6 +- src/core/task/tools/autoApprove.ts | 10 +- .../ListCodeDefinitionNamesToolHandler.ts | 6 +- .../tools/handlers/ListFilesToolHandler.ts | 6 +- .../tools/handlers/ReadFileToolHandler.ts | 6 +- .../tools/handlers/SearchFilesToolHandler.ts | 5 +- .../tools/handlers/WriteToFileToolHandler.ts | 10 +- src/core/workspace/MigrationReporter.ts | 167 +++++++++++ src/core/workspace/WorkspaceResolver.ts | 275 ++++++++++++++++++ src/core/workspace/WorkspaceRoot.ts | 32 ++ src/core/workspace/WorkspaceRootManager.ts | 261 +++++++++++++++++ .../__tests__/WorkspaceResolver.test.ts | 206 +++++++++++++ src/core/workspace/index.ts | 18 ++ src/integrations/dify/dify-integration.ts | 4 +- src/integrations/editor/DiffViewProvider.ts | 6 +- src/services/glob/list-files.ts | 6 +- src/services/ripgrep/index.ts | 8 +- src/utils/fs.ts | 12 +- src/utils/path.ts | 24 +- src/utils/storage.ts | 13 +- tsconfig.json | 3 + 27 files changed, 1073 insertions(+), 53 deletions(-) create mode 100644 .changeset/small-lions-train.md create mode 100644 src/core/workspace/MigrationReporter.ts create mode 100644 src/core/workspace/WorkspaceResolver.ts create mode 100644 src/core/workspace/WorkspaceRoot.ts create mode 100644 src/core/workspace/WorkspaceRootManager.ts create mode 100644 src/core/workspace/__tests__/WorkspaceResolver.test.ts create mode 100644 src/core/workspace/index.ts diff --git a/.changeset/small-lions-train.md b/.changeset/small-lions-train.md new file mode 100644 index 00000000..a57aa7c3 --- /dev/null +++ b/.changeset/small-lions-train.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Setup Raw Structure for implementing multi-workspace support with WorkspaceRoot diff --git a/src/core/controller/file/createRuleFile.ts b/src/core/controller/file/createRuleFile.ts index 49de429f..ef780634 100644 --- a/src/core/controller/file/createRuleFile.ts +++ b/src/core/controller/file/createRuleFile.ts @@ -1,7 +1,7 @@ import { refreshClineRulesToggles } from "@core/context/instructions/user-instructions/cline-rules" import { createRuleFile as createRuleFileImpl } from "@core/context/instructions/user-instructions/rule-helpers" +import { getWorkspaceBasename } from "@core/workspace" import { RuleFile, RuleFileRequest } from "@shared/proto/cline/file" -import * as path from "path" import { refreshWorkflowToggles } from "@/core/context/instructions/user-instructions/workflows" import { HostProvider } from "@/hosts/host-provider" import { ShowMessageType } from "@/shared/proto/host/window" @@ -68,7 +68,7 @@ export async function createRuleFile(controller: Controller, request: RuleFileRe return RuleFile.create({ filePath: filePath, - displayName: path.basename(filePath), + displayName: getWorkspaceBasename(filePath, "Controller.createRuleFile"), alreadyExists: fileExists, }) } diff --git a/src/core/controller/file/deleteRuleFile.ts b/src/core/controller/file/deleteRuleFile.ts index 450b077f..21f0ed60 100644 --- a/src/core/controller/file/deleteRuleFile.ts +++ b/src/core/controller/file/deleteRuleFile.ts @@ -1,6 +1,6 @@ import { deleteRuleFile as deleteRuleFileImpl } from "@core/context/instructions/user-instructions/rule-helpers" +import { getWorkspaceBasename } from "@core/workspace" import { RuleFile, RuleFileRequest } from "@shared/proto/cline/file" -import * as path from "path" import { HostProvider } from "@/hosts/host-provider" import { ShowMessageType } from "@/shared/proto/host/window" import { Controller } from ".." @@ -40,7 +40,7 @@ export async function deleteRuleFile(controller: Controller, request: RuleFileRe //await refreshWorkflowToggles(controller.context, cwd) await controller.postStateToWebview() - const fileName = path.basename(request.rulePath) + const fileName = getWorkspaceBasename(request.rulePath, "Controller.deleteRuleFile") const fileTypeName = request.type === "workflow" ? "workflow" : "rule" diff --git a/src/core/controller/file/ifFileExistsRelativePath.ts b/src/core/controller/file/ifFileExistsRelativePath.ts index 781ce81e..411ac7c9 100644 --- a/src/core/controller/file/ifFileExistsRelativePath.ts +++ b/src/core/controller/file/ifFileExistsRelativePath.ts @@ -1,7 +1,7 @@ +import { workspaceResolver } from "@core/workspace" import { BooleanResponse, StringRequest } from "@shared/proto/cline/common" import { getWorkspacePath } from "@utils/path" import * as fs from "fs" -import * as path from "path" import { Controller } from ".." /** @@ -25,7 +25,12 @@ export async function ifFileExistsRelativePath(_controller: Controller, request: } // Resolve the relative path to absolute path - const absolutePath = path.resolve(workspacePath, request.value) + const resolvedPath = workspaceResolver.resolveWorkspacePath( + workspacePath, + request.value, + "Controller.ifFileExistsRelativePath", + ) + const absolutePath = typeof resolvedPath === "string" ? resolvedPath : resolvedPath.absolutePath // Check if the file exists try { return BooleanResponse.create({ value: fs.statSync(absolutePath).isFile() }) diff --git a/src/core/controller/file/openFileRelativePath.ts b/src/core/controller/file/openFileRelativePath.ts index 53950dad..b1e998ed 100644 --- a/src/core/controller/file/openFileRelativePath.ts +++ b/src/core/controller/file/openFileRelativePath.ts @@ -1,7 +1,7 @@ +import { workspaceResolver } from "@core/workspace" import { openFile as openFileIntegration } from "@integrations/misc/open-file" import { Empty, StringRequest } from "@shared/proto/cline/common" import { getWorkspacePath } from "@utils/path" -import * as path from "path" import { Controller } from ".." /** @@ -20,7 +20,12 @@ export async function openFileRelativePath(_controller: Controller, request: Str if (request.value) { // Resolve the relative path to absolute path - const absolutePath = path.resolve(workspacePath, request.value) + const resolvedPath = workspaceResolver.resolveWorkspacePath( + workspacePath, + request.value, + "Controller.openFileRelativePath", + ) + const absolutePath = typeof resolvedPath === "string" ? resolvedPath : resolvedPath.absolutePath // Open the file using the existing integration openFileIntegration(absolutePath) diff --git a/src/core/controller/file/toggleClineRule.ts b/src/core/controller/file/toggleClineRule.ts index b0fe5fe8..333dc675 100644 --- a/src/core/controller/file/toggleClineRule.ts +++ b/src/core/controller/file/toggleClineRule.ts @@ -1,4 +1,4 @@ -import path from "node:path" +import { getWorkspaceBasename } from "@core/workspace" import type { ToggleClineRuleRequest } from "@shared/proto/cline/file" import { ToggleClineRules } from "@shared/proto/cline/file" import { telemetryService } from "@/services/telemetry" @@ -36,14 +36,7 @@ export async function toggleClineRule(controller: Controller, request: ToggleCli // Track rule toggle telemetry with current task context if (controller.task?.ulid) { // Extract just the filename for privacy (no full paths) - const ruleFileName = path.basename(rulePath) - telemetryService.captureClineRuleToggled(controller.task.ulid, ruleFileName, enabled, isGlobal) - } - - // Track rule toggle telemetry with current task context - if (controller.task?.ulid) { - // Extract just the filename for privacy (no full paths) - const ruleFileName = path.basename(rulePath) + const ruleFileName = getWorkspaceBasename(rulePath, "Controller.toggleClineRule") telemetryService.captureClineRuleToggled(controller.task.ulid, ruleFileName, enabled, isGlobal) } diff --git a/src/core/controller/task/deleteAllTaskHistory.ts b/src/core/controller/task/deleteAllTaskHistory.ts index 88b5c51d..1b891c04 100644 --- a/src/core/controller/task/deleteAllTaskHistory.ts +++ b/src/core/controller/task/deleteAllTaskHistory.ts @@ -138,7 +138,11 @@ async function cleanupTaskFiles(controller: Controller, preserveTaskIds: string[ // Delete only non-preserved task directories for (const dir of taskDirs) { if (!preserveTaskIds.includes(dir)) { - await fs.rm(path.join(taskDirPath, dir), { recursive: true, force: true }) + // Task dir path is not workspace specific + await fs.rm(path.join(taskDirPath, dir), { + recursive: true, + force: true, + }) } } } diff --git a/src/core/task/tools/autoApprove.ts b/src/core/task/tools/autoApprove.ts index 31e1bdc0..51428bad 100644 --- a/src/core/task/tools/autoApprove.ts +++ b/src/core/task/tools/autoApprove.ts @@ -1,7 +1,7 @@ import { ToolUseName } from "@core/assistant-message" +import { resolveWorkspacePath } from "@core/workspace" import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" -import * as path from "path" -import { getCwd, getDesktopDir } from "@/utils/path" +import { getCwd, getDesktopDir, isLocatedInPath } from "@/utils/path" export class AutoApprove { autoApprovalSettings: AutoApprovalSettings @@ -53,9 +53,9 @@ export class AutoApprove { async shouldAutoApproveToolWithPath(blockname: ToolUseName, autoApproveActionpath: string | undefined): Promise { let isLocalRead: boolean = false if (autoApproveActionpath) { - const cwd = path.normalize(await getCwd(getDesktopDir())) - const absolutePath = path.resolve(cwd, autoApproveActionpath) - isLocalRead = absolutePath.startsWith(cwd) + const cwd = await getCwd(getDesktopDir()) + const absolutePath = resolveWorkspacePath(cwd, autoApproveActionpath, "AutoApprove.shouldAutoApproveToolWithPath") + isLocalRead = isLocatedInPath(cwd, absolutePath) } else { // If we do not get a path for some reason, default to a (safer) false return isLocalRead = false diff --git a/src/core/task/tools/handlers/ListCodeDefinitionNamesToolHandler.ts b/src/core/task/tools/handlers/ListCodeDefinitionNamesToolHandler.ts index 7ed7cff0..39a7e36b 100644 --- a/src/core/task/tools/handlers/ListCodeDefinitionNamesToolHandler.ts +++ b/src/core/task/tools/handlers/ListCodeDefinitionNamesToolHandler.ts @@ -1,7 +1,7 @@ import type { ToolUse } from "@core/assistant-message" +import { getWorkspaceBasename, resolveWorkspacePath } from "@core/workspace" import { parseSourceCodeForDefinitionsTopLevel } from "@services/tree-sitter" import { getReadablePath, isLocatedInWorkspace } from "@utils/path" -import * as path from "path" import { formatResponse } from "@/core/prompts/responses" import { telemetryService } from "@/services/telemetry" import type { ToolResponse } from "../../index" @@ -57,7 +57,7 @@ export class ListCodeDefinitionNamesToolHandler implements IFullyManagedTool { } config.taskState.consecutiveMistakeCount = 0 - const absolutePath = path.resolve(config.cwd, relDirPath!) + const absolutePath = resolveWorkspacePath(config.cwd, relDirPath!, "ListCodeDefinitionNamesToolHandler.execute") // Execute the actual parse source code operation const result = await parseSourceCodeForDefinitionsTopLevel(absolutePath, config.services.clineIgnoreController) @@ -81,7 +81,7 @@ export class ListCodeDefinitionNamesToolHandler implements IFullyManagedTool { telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, true, true) } else { // Manual approval flow - const notificationMessage = `Cline wants to analyze code definitions in ${path.basename(absolutePath)}` + const notificationMessage = `Cline wants to analyze code definitions in ${getWorkspaceBasename(absolutePath, "ListCodeDefinitionNamesToolHandler.notification")}` // Show notification showNotificationForApprovalIfAutoApprovalEnabled( diff --git a/src/core/task/tools/handlers/ListFilesToolHandler.ts b/src/core/task/tools/handlers/ListFilesToolHandler.ts index 31630ac4..dee335c4 100644 --- a/src/core/task/tools/handlers/ListFilesToolHandler.ts +++ b/src/core/task/tools/handlers/ListFilesToolHandler.ts @@ -1,8 +1,8 @@ import type { ToolUse } from "@core/assistant-message" import { formatResponse } from "@core/prompts/responses" +import { getWorkspaceBasename, resolveWorkspacePath } from "@core/workspace" import { listFiles } from "@services/glob/list-files" import { getReadablePath, isLocatedInWorkspace } from "@utils/path" -import * as path from "path" import { telemetryService } from "@/services/telemetry" import type { ToolResponse } from "../../index" import { showNotificationForApprovalIfAutoApprovalEnabled } from "../../utils" @@ -62,7 +62,7 @@ export class ListFilesToolHandler implements IFullyManagedTool { } config.taskState.consecutiveMistakeCount = 0 - const absolutePath = path.resolve(config.cwd, relDirPath!) + const absolutePath = resolveWorkspacePath(config.cwd, relDirPath!, "ListFilesToolHandler.execute") // Execute the actual list files operation const [files, didHitLimit] = await listFiles(absolutePath, recursive, 200) @@ -89,7 +89,7 @@ export class ListFilesToolHandler implements IFullyManagedTool { telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, true, true) } else { // Manual approval flow - const notificationMessage = `Cline wants to view directory ${path.basename(absolutePath)}/` + const notificationMessage = `Cline wants to view directory ${getWorkspaceBasename(absolutePath, "ListFilesToolHandler.notification")}/` // Show notification showNotificationForApprovalIfAutoApprovalEnabled( diff --git a/src/core/task/tools/handlers/ReadFileToolHandler.ts b/src/core/task/tools/handlers/ReadFileToolHandler.ts index 3296116e..c34188a1 100644 --- a/src/core/task/tools/handlers/ReadFileToolHandler.ts +++ b/src/core/task/tools/handlers/ReadFileToolHandler.ts @@ -1,8 +1,8 @@ import type { ToolUse } from "@core/assistant-message" import { formatResponse } from "@core/prompts/responses" +import { getWorkspaceBasename, resolveWorkspacePath } from "@core/workspace" import { extractFileContent } from "@integrations/misc/extract-file-content" import { getReadablePath, isLocatedInWorkspace } from "@utils/path" -import * as path from "path" import { telemetryService } from "@/services/telemetry" import { ClineSayTool } from "@/shared/ExtensionMessage" import type { ToolResponse } from "../../index" @@ -65,7 +65,7 @@ export class ReadFileToolHandler implements IFullyManagedTool { } config.taskState.consecutiveMistakeCount = 0 - const absolutePath = path.resolve(config.cwd, relPath!) + const absolutePath = resolveWorkspacePath(config.cwd, relPath!, "ReadFileToolHandler.execute") // Handle approval flow const sharedMessageProps = { @@ -87,7 +87,7 @@ export class ReadFileToolHandler implements IFullyManagedTool { telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, true, true) } else { // Manual approval flow - const notificationMessage = `Cline wants to read ${path.basename(absolutePath)}` + const notificationMessage = `Cline wants to read ${getWorkspaceBasename(absolutePath, "ReadFileToolHandler.notification")}` // Show notification showNotificationForApprovalIfAutoApprovalEnabled( diff --git a/src/core/task/tools/handlers/SearchFilesToolHandler.ts b/src/core/task/tools/handlers/SearchFilesToolHandler.ts index 5eb05578..a656febd 100644 --- a/src/core/task/tools/handlers/SearchFilesToolHandler.ts +++ b/src/core/task/tools/handlers/SearchFilesToolHandler.ts @@ -1,8 +1,8 @@ import type { ToolUse } from "@core/assistant-message" import { regexSearchFiles } from "@services/ripgrep" import { getReadablePath, isLocatedInWorkspace } from "@utils/path" -import * as path from "path" import { formatResponse } from "@/core/prompts/responses" +import { resolveWorkspacePath } from "@/core/workspace/WorkspaceResolver" import { telemetryService } from "@/services/telemetry" import { ClineSayTool } from "@/shared/ExtensionMessage" import type { ToolResponse } from "../../index" @@ -72,7 +72,8 @@ export class SearchFilesToolHandler implements IFullyManagedTool { } config.taskState.consecutiveMistakeCount = 0 - const absolutePath = path.resolve(config.cwd, relDirPath!) + const absolutePath = resolveWorkspacePath(config.cwd, relDirPath!, "SearchFilesTool.execute") + // Execute the actual regex search operation const results = await regexSearchFiles( config.cwd, diff --git a/src/core/task/tools/handlers/WriteToFileToolHandler.ts b/src/core/task/tools/handlers/WriteToFileToolHandler.ts index fa17b7b5..c1256e20 100644 --- a/src/core/task/tools/handlers/WriteToFileToolHandler.ts +++ b/src/core/task/tools/handlers/WriteToFileToolHandler.ts @@ -2,12 +2,12 @@ import { setTimeout as setTimeoutPromise } from "node:timers/promises" import type { ToolUse } from "@core/assistant-message" import { constructNewFileContent } from "@core/assistant-message/diff" import { formatResponse } from "@core/prompts/responses" +import { getWorkspaceBasename, resolveWorkspacePath } from "@core/workspace" import { processFilesIntoText } from "@integrations/misc/extract-text" import { ClineSayTool } from "@shared/ExtensionMessage" import { fileExistsAtPath } from "@utils/fs" import { getReadablePath, isLocatedInWorkspace } from "@utils/path" import { fixModelHtmlEscaping, removeInvalidChars } from "@utils/string" -import * as path from "path" import { telemetryService } from "@/services/telemetry" import type { ToolResponse } from "../../index" import { showNotificationForApprovalIfAutoApprovalEnabled } from "../../utils" @@ -176,7 +176,7 @@ export class WriteToFileToolHandler implements IFullyManagedTool { await setTimeoutPromise(3_500) } else { // Manual approval flow with detailed feedback handling - const notificationMessage = `Cline wants to ${fileExists ? "edit" : "create"} ${path.basename(relPath)}` + const notificationMessage = `Cline wants to ${fileExists ? "edit" : "create"} ${getWorkspaceBasename(relPath, "WriteToFile.notification")}` // Show notification showNotificationForApprovalIfAutoApprovalEnabled( @@ -331,7 +331,11 @@ export class WriteToFileToolHandler implements IFullyManagedTool { if (config.services.diffViewProvider.editType !== undefined) { fileExists = config.services.diffViewProvider.editType === "modify" } else { - const absolutePath = path.resolve(config.cwd, relPath) + const absolutePath = resolveWorkspacePath( + config.cwd, + relPath, + "WriteToFileToolHandler.validateAndPrepareFileOperation", + ) fileExists = await fileExistsAtPath(absolutePath) config.services.diffViewProvider.editType = fileExists ? "modify" : "create" } diff --git a/src/core/workspace/MigrationReporter.ts b/src/core/workspace/MigrationReporter.ts new file mode 100644 index 00000000..ddbdef99 --- /dev/null +++ b/src/core/workspace/MigrationReporter.ts @@ -0,0 +1,167 @@ +/** + * Handles formatting and presentation of workspace migration reports + * + * Separated from WorkspaceResolver to follow Single Responsibility Principle. + * This class focuses purely on report generation and formatting. + */ + +/** + * Tracks path resolution usage for migration planning + */ +export interface UsageStats { + count: number + examples: string[] + lastUsed: Date +} + +/** + * Configuration options for report generation + */ +interface ReportOptions { + includeExamples?: boolean + includeHighUsage?: boolean + highUsageThreshold?: number + sortByUsage?: boolean +} + +/** + * Handles generation and formatting of migration reports + */ +export class MigrationReporter { + private readonly defaultOptions: Required = { + includeExamples: true, + includeHighUsage: true, + highUsageThreshold: 100, + sortByUsage: true, + } + + /** + * Generate a comprehensive migration report from usage statistics + * @param usageMap - Map of component names to their usage statistics + * @param traceEnabled - Whether tracing is currently enabled + * @param options - Optional configuration for report generation + * @returns Formatted migration report string + */ + generateReport(usageMap: Map, traceEnabled: boolean, options: ReportOptions = {}): string { + const config = { ...this.defaultOptions, ...options } + const entries = this.prepareEntries(usageMap, config.sortByUsage) + + let report = this.generateHeader(entries.length, traceEnabled) + report += this.generateComponentDetails(entries, config) + report += this.generateSummary(entries) + + if (config.includeHighUsage) { + report += this.generateHighUsageSection(entries, config.highUsageThreshold) + } + + return report + } + + /** + * Generate a simplified summary report + * @param usageMap - Map of component names to their usage statistics + * @returns Brief summary string + */ + generateSummary(entries: Array<[string, UsageStats]>): string { + const totalCalls = entries.reduce((sum, [_, stats]) => sum + stats.count, 0) + + let summary = `\n=== Summary ===\n` + summary += `Total path resolution calls: ${totalCalls}\n` + + return summary + } + + /** + * Prepare and optionally sort the usage entries + */ + private prepareEntries(usageMap: Map, sortByUsage: boolean): Array<[string, UsageStats]> { + const entries = Array.from(usageMap.entries()) + + if (sortByUsage) { + return entries.sort((a, b) => b[1].count - a[1].count) + } + + return entries + } + + /** + * Generate the report header section + */ + private generateHeader(componentCount: number, traceEnabled: boolean): string { + let header = "=== Multi-Root Migration Report ===\n" + header += `Total components using single-root: ${componentCount}\n` + header += `Trace enabled: ${traceEnabled}\n\n` + return header + } + + /** + * Generate detailed component usage information + */ + private generateComponentDetails(entries: Array<[string, UsageStats]>, config: Required): string { + let details = "" + + entries.forEach(([context, stats]) => { + details += `${context}:\n` + details += ` Calls: ${stats.count}\n` + details += ` Last used: ${stats.lastUsed.toISOString()}\n` + + if (config.includeExamples && stats.examples.length > 0) { + details += ` Example paths:\n` + stats.examples.forEach((ex) => { + details += ` - "${ex}"\n` + }) + } + details += "\n" + }) + + return details + } + + /** + * Generate high-usage components section + */ + private generateHighUsageSection(entries: Array<[string, UsageStats]>, threshold: number): string { + const highUsageComponents = entries + .filter(([_, stats]) => stats.count > threshold) + .map(([context, stats]) => ({ context, count: stats.count })) + + if (highUsageComponents.length === 0) { + return "" + } + + let section = `\n=== High-Usage Components ===\n` + section += `(Operations with >${threshold} calls)\n` + highUsageComponents.forEach((h) => { + section += ` - ${h.context}: ${h.count} calls\n` + }) + + return section + } + + /** + * Generate a JSON representation of the usage data + * @param usageMap - Map of component names to their usage statistics + * @returns JSON string representation + */ + generateJsonReport(usageMap: Map): string { + const data = Object.fromEntries(usageMap) + return JSON.stringify(data, null, 2) + } + + /** + * Generate a CSV representation of the usage data + * @param usageMap - Map of component names to their usage statistics + * @returns CSV string representation + */ + generateCsvReport(usageMap: Map): string { + const entries = Array.from(usageMap.entries()) + let csv = "Component,Calls,LastUsed,ExamplePaths\n" + + entries.forEach(([context, stats]) => { + const examples = stats.examples.join("; ") + csv += `"${context}",${stats.count},"${stats.lastUsed.toISOString()}","${examples}"\n` + }) + + return csv + } +} diff --git a/src/core/workspace/WorkspaceResolver.ts b/src/core/workspace/WorkspaceResolver.ts new file mode 100644 index 00000000..2c932f7a --- /dev/null +++ b/src/core/workspace/WorkspaceResolver.ts @@ -0,0 +1,275 @@ +/** + * Workspace path resolution with migration tracing for multi-workspace support + * + * Phase 0: Acts as a tracer to identify all single-root path operations + * Phase 1+: Will handle multi-root path resolution + */ + +import { Logger } from "@services/logging/Logger" +import * as path from "path" +import { MigrationReporter, type UsageStats } from "./MigrationReporter" +import { WorkspaceRoot } from "./WorkspaceRoot" + +/** + * Maximum number of example paths to store per component for debugging purposes. + * This limit prevents excessive memory usage while providing enough examples + * to understand usage patterns during migration analysis. + */ +const MAX_EXAMPLE_PATHS = 5 + +export class WorkspaceResolver { + private usageMap = new Map() + private traceEnabled = process.env.MULTI_ROOT_TRACE === "true" || process.env.NODE_ENV === "development" + + /** + * Track usage statistics for a given context and path + * @param context - Component/handler name for tracking usage + * @param examplePath - The path to track as an example + */ + private trackUsage(context: string, examplePath: string): void { + const stats = this.usageMap.get(context) || { + count: 0, + examples: [], + lastUsed: new Date(), + } + + stats.count++ + stats.lastUsed = new Date() + + // Keep up to MAX_EXAMPLE_PATHS example paths for debugging + if (stats.examples.length < MAX_EXAMPLE_PATHS && !stats.examples.includes(examplePath)) { + stats.examples.push(examplePath) + } + + this.usageMap.set(context, stats) + } + + /** + * Phase 0: Traces single-root path resolution for migration planning + * Phase 1+: Will resolve path against multiple workspace roots + * + * @param cwdOrRoots - Current working directory (Phase 0) or array of workspace roots (Phase 1+) + * @param relativePath - The relative path to resolve + * @param context - Component/handler name for tracking usage + * @returns Absolute path (Phase 0) or object with path and root (Phase 1+) + */ + resolveWorkspacePath( + cwdOrRoots: string | WorkspaceRoot[], + relativePath: string, + context?: string, + ): string | { absolutePath: string; root: WorkspaceRoot } { + // Phase 0: Single-root tracer mode + if (typeof cwdOrRoots === "string") { + return this.resolveSingleRootPath(cwdOrRoots, relativePath, context) + } + + // Phase 1+: Multi-root resolution + return this.resolveMultiRootPath(cwdOrRoots, relativePath) + } + + /** + * Resolves a path against a single workspace root (Phase 0) + * + * @param cwd - Current working directory + * @param relativePath - The relative path to resolve + * @param context - Component/handler name for tracking usage + * @returns Absolute path + */ + private resolveSingleRootPath(cwd: string, relativePath: string, context?: string): string { + // Track usage for migration planning + if (context) { + this.trackUsage(context, relativePath) + + if (this.traceEnabled) { + Logger.debug(`[MULTI-ROOT-TRACE] ${context}: resolving "${relativePath}" against "${cwd}"`) + } + } + + return path.resolve(cwd, relativePath) + } + + /** + * Resolves a path against multiple workspace roots (Phase 1+) + * + * @param workspaceRoots - Array of workspace roots + * @param relativePath - The relative path to resolve + * @returns Object with absolute path and matching root + */ + private resolveMultiRootPath( + workspaceRoots: WorkspaceRoot[], + relativePath: string, + ): { absolutePath: string; root: WorkspaceRoot } { + // Handle absolute paths + if (path.isAbsolute(relativePath)) { + return this.resolveAbsolutePath(workspaceRoots, relativePath) + } + + // Handle relative paths + return this.resolveRelativePath(workspaceRoots, relativePath) + } + + /** + * Resolves an absolute path against workspace roots + * + * @param workspaceRoots - Array of workspace roots + * @param absolutePath - The absolute path to resolve + * @returns Object with absolute path and matching root + */ + private resolveAbsolutePath( + workspaceRoots: WorkspaceRoot[], + absolutePath: string, + ): { absolutePath: string; root: WorkspaceRoot } { + const matchingRoot = workspaceRoots.find((root) => absolutePath.startsWith(root.path)) + return { + absolutePath, + root: matchingRoot || workspaceRoots[0], // fallback to primary + } + } + + /** + * Resolves a relative path against workspace roots + * + * @param workspaceRoots - Array of workspace roots + * @param relativePath - The relative path to resolve + * @returns Object with absolute path and matching root + */ + private resolveRelativePath( + workspaceRoots: WorkspaceRoot[], + relativePath: string, + ): { absolutePath: string; root: WorkspaceRoot } { + // Check which roots have this relative path + const candidateRoots: WorkspaceRoot[] = [] + for (const root of workspaceRoots) { + // const testPath = path.join(root.path, relativePath) + // In Phase 1, check if path exists + // For now, just add all roots as candidates + candidateRoots.push(root) + } + + return this.selectBestRoot(workspaceRoots, candidateRoots, relativePath) + } + + /** + * Selects the best root from candidate roots using disambiguation logic + * + * @param workspaceRoots - All available workspace roots + * @param candidateRoots - Candidate roots that could contain the path + * @param relativePath - The relative path being resolved + * @returns Object with absolute path and selected root + */ + private selectBestRoot( + workspaceRoots: WorkspaceRoot[], + candidateRoots: WorkspaceRoot[], + relativePath: string, + ): { absolutePath: string; root: WorkspaceRoot } { + // Disambiguation logic (simplified for Phase 0) + if (candidateRoots.length === 0) { + // Path doesn't exist in any root, use primary + return { + absolutePath: path.resolve(workspaceRoots[0].path, relativePath), + root: workspaceRoots[0], + } + } + + if (candidateRoots.length === 1) { + // Unambiguous + return { + absolutePath: path.resolve(candidateRoots[0].path, relativePath), + root: candidateRoots[0], + } + } + + // Multiple matches - need disambiguation + // Phase 2: This will trigger UI picker + // For now, use primary root if it's a candidate, otherwise first match + const primaryRoot = workspaceRoots[0] + const selectedRoot = candidateRoots.find((r) => r.path === primaryRoot.path) || candidateRoots[0] + + return { + absolutePath: path.resolve(selectedRoot.path, relativePath), + root: selectedRoot, + } + } + + /** + * Get migration report showing all single-root usage patterns + * Currently this function is mainly called by the vscode debugger + */ + getMigrationReport(): string { + const reporter = new MigrationReporter() + return reporter.generateReport(this.usageMap, this.traceEnabled) + } + + /** + * Get raw usage statistics for external analysis + * @returns Map of component names to their usage statistics + */ + getUsageStats(): Map { + return new Map(this.usageMap) + } + + /** + * Clear usage statistics (useful for testing) + */ + clearUsageStats(): void { + this.usageMap.clear() + } + + /** + * Export usage data as JSON for analysis + */ + exportUsageData(): Record { + return Object.fromEntries(this.usageMap) + } + + /** + * Phase 0: Instance method for getting basename with tracking + * Phase 1+: Will handle basename for multi-workspace paths + * + * @param filePath - The file path to get basename from + * @param context - Component/handler name for tracking usage + * @returns The basename of the path + */ + getBasename(filePath: string, context?: string): string { + // Track usage for migration planning + if (!context?.length) { + return path.basename(filePath) + } + this.trackUsage(context, filePath) + + // Phase 0: Just wrap existing behavior + const result = path.basename(filePath) + + if (this.traceEnabled) { + Logger.debug(`[MULTI-ROOT-TRACE] ${context}: getting basename for "${filePath}"`) + } + + return result + } +} + +// Export singleton instance +export const workspaceResolver = new WorkspaceResolver() + +/** + * Phase 0: Convenience function for easy migration from path.resolve() + * This is what we'll use to replace existing path.resolve(cwd, ...) calls + */ +export function resolveWorkspacePath(cwd: string, relativePath: string, context?: string): string { + return workspaceResolver.resolveWorkspacePath(cwd, relativePath, context) as string +} + +/** + * Helper to check if we're in trace mode + */ +export function isWorkspaceTraceEnabled(): boolean { + return process.env.MULTI_ROOT_TRACE === "true" || process.env.NODE_ENV === "development" +} + +/** + * Phase 0: Convenience function for path.basename with tracking + * This is what we'll use to replace existing path.basename() calls + */ +export function getWorkspaceBasename(filePath: string, context?: string): string { + return workspaceResolver.getBasename(filePath, context) +} diff --git a/src/core/workspace/WorkspaceRoot.ts b/src/core/workspace/WorkspaceRoot.ts new file mode 100644 index 00000000..c3b9e6ba --- /dev/null +++ b/src/core/workspace/WorkspaceRoot.ts @@ -0,0 +1,32 @@ +/** + * Workspace root types and interfaces for multi-workspace support + */ + +export enum VcsType { + None = "none", + Git = "git", + Mercurial = "mercurial", +} + +export interface WorkspaceRoot { + path: string // Absolute path to the workspace root + name?: string // Optional display name for the workspace (auto-derived from path if not provided) + vcs: VcsType // Version control system type for this root + commitHash?: string // Optional latest commit hash/changeset ID for VCS tracking +} + +// Example usage: +// const workspaceRoots: WorkspaceRoot[] = [ +// { +// path: "/Users/dev/frontend", +// name: "frontend", +// vcs: VcsType.Git, +// commitHash: "a1b2c3d4e5f6789" +// }, +// { +// path: "/Users/dev/backend", +// name: "backend", +// vcs: VcsType.Git, +// commitHash: "f6e5d4c3b2a1987" +// } +// ] diff --git a/src/core/workspace/WorkspaceRootManager.ts b/src/core/workspace/WorkspaceRootManager.ts new file mode 100644 index 00000000..20d49540 --- /dev/null +++ b/src/core/workspace/WorkspaceRootManager.ts @@ -0,0 +1,261 @@ +/** + * WorkspaceRootManager - Central manager for multi-workspace operations + * This class handles workspace root resolution, path mapping, and workspace context + */ + +import { execa } from "execa" +import * as path from "path" +import { getLatestGitCommitHash } from "../../utils/git" +import { VcsType, WorkspaceRoot } from "./WorkspaceRoot" + +export interface WorkspaceContext { + workspaceRoots: WorkspaceRoot[] + primaryRoot: WorkspaceRoot + currentRoot?: WorkspaceRoot +} + +export class WorkspaceRootManager { + private roots: WorkspaceRoot[] = [] + private primaryIndex: number = 0 + + constructor(roots: WorkspaceRoot[] = [], primaryIndex: number = 0) { + this.roots = roots + this.primaryIndex = Math.min(primaryIndex, Math.max(0, roots.length - 1)) + } + + /** + * Initialize from a single cwd for backward compatibility + */ + static async fromLegacyCwd(cwd: string): Promise { + const vcs = await WorkspaceRootManager.detectVcs(cwd) + const gitHash = vcs === VcsType.Git ? await getLatestGitCommitHash(cwd) : null + const commitHash = gitHash === null ? undefined : gitHash + + const root: WorkspaceRoot = { + path: cwd, + name: path.basename(cwd), + vcs, + commitHash, + } + + return new WorkspaceRootManager([root], 0) + } + + /** + * Detect version control system for a directory + */ + private static async detectVcs(dirPath: string): Promise { + try { + // Check for Git + await execa("git", ["rev-parse", "--git-dir"], { cwd: dirPath }) + return VcsType.Git + } catch { + // Not a git repo + } + + try { + // Check for Mercurial + await execa("hg", ["root"], { cwd: dirPath }) + return VcsType.Mercurial + } catch { + // Not a mercurial repo + } + + return VcsType.None + } + + /** + * Add a new workspace root + */ + async addRoot(rootPath: string, name?: string): Promise { + const vcs = await WorkspaceRootManager.detectVcs(rootPath) + const gitHash = vcs === VcsType.Git ? await getLatestGitCommitHash(rootPath) : null + const commitHash = gitHash === null ? undefined : gitHash + + const root: WorkspaceRoot = { + path: rootPath, + name: name || path.basename(rootPath), + vcs, + commitHash, + } + + this.roots.push(root) + } + + /** + * Remove a workspace root by path + */ + removeRoot(path: string): boolean { + const index = this.roots.findIndex((r) => r.path === path) + if (index === -1) { + return false + } + + this.roots.splice(index, 1) + + // Adjust primary index if needed + if (this.primaryIndex >= this.roots.length) { + this.primaryIndex = Math.max(0, this.roots.length - 1) + } + + return true + } + + /** + * Get all workspace roots + */ + getRoots(): WorkspaceRoot[] { + return [...this.roots] + } + + /** + * Get the primary workspace root + */ + getPrimaryRoot(): WorkspaceRoot | undefined { + return this.roots[this.primaryIndex] + } + + /** + * Set the primary workspace root by index + */ + setPrimaryIndex(index: number): void { + if (index >= 0 && index < this.roots.length) { + this.primaryIndex = index + } + } + + /** + * Find the workspace root that contains the given absolute path + */ + resolvePathToRoot(absolutePath: string): WorkspaceRoot | undefined { + // Sort roots by path length (longest first) to handle nested workspaces + const sortedRoots = [...this.roots].sort((a, b) => b.path.length - a.path.length) + + for (const root of sortedRoots) { + if (absolutePath.startsWith(root.path)) { + return root + } + } + + return undefined + } + + /** + * Find workspace root by name + */ + getRootByName(name: string): WorkspaceRoot | undefined { + return this.roots.find((r) => r.name === name) + } + + /** + * Get workspace root by index + */ + getRootByIndex(index: number): WorkspaceRoot | undefined { + return this.roots[index] + } + + /** + * Check if a path is within any workspace root + */ + isPathInWorkspace(absolutePath: string): boolean { + return this.resolvePathToRoot(absolutePath) !== undefined + } + + /** + * Get relative path from workspace root + */ + getRelativePathFromRoot(absolutePath: string, root?: WorkspaceRoot): string | undefined { + const targetRoot = root || this.resolvePathToRoot(absolutePath) + if (!targetRoot) { + return undefined + } + + return path.relative(targetRoot.path, absolutePath) + } + + /** + * Create workspace context for tool execution + */ + createContext(currentRoot?: WorkspaceRoot): WorkspaceContext { + return { + workspaceRoots: this.getRoots(), + primaryRoot: this.getPrimaryRoot()!, + currentRoot: currentRoot || this.getPrimaryRoot(), + } + } + + /** + * Serialize for storage + */ + toJSON(): { roots: WorkspaceRoot[]; primaryIndex: number } { + return { + roots: this.roots, + primaryIndex: this.primaryIndex, + } + } + + /** + * Deserialize from storage + */ + static fromJSON(data: { roots: WorkspaceRoot[]; primaryIndex: number }): WorkspaceRootManager { + return new WorkspaceRootManager(data.roots, data.primaryIndex) + } + + /** + * Get a summary string for display + */ + getSummary(): string { + if (this.roots.length === 0) { + return "No workspace roots configured" + } + + if (this.roots.length === 1) { + return `Single workspace: ${this.roots[0].name || this.roots[0].path}` + } + + const primary = this.getPrimaryRoot() + return `Multi-workspace (${this.roots.length} roots)\nPrimary: ${primary?.name || primary?.path}\nAdditional: ${this.roots + .filter((_, i) => i !== this.primaryIndex) + .map((r) => r.name || path.basename(r.path)) + .join(", ")}` + } + + /** + * Check if this is a single-root workspace (for backward compatibility) + */ + isSingleRoot(): boolean { + return this.roots.length === 1 + } + + /** + * Get the single root if this is a single-root workspace + * Throws if multiple roots exist + */ + getSingleRoot(): WorkspaceRoot { + if (this.roots.length !== 1) { + throw new Error(`Expected single root, but found ${this.roots.length} roots`) + } + return this.roots[0] + } + + /** + * Update commit hashes for all Git repositories + */ + async updateCommitHashes(): Promise { + for (const root of this.roots) { + if (root.vcs === VcsType.Git) { + const gitHash = await getLatestGitCommitHash(root.path) + root.commitHash = gitHash === null ? undefined : gitHash + } + } + } +} + +// Export for use in Task and Controller +export function createLegacyWorkspaceRoot(cwd: string): WorkspaceRoot { + return { + path: cwd, + name: path.basename(cwd), + vcs: VcsType.None, // Will be detected properly during initialization + } +} diff --git a/src/core/workspace/__tests__/WorkspaceResolver.test.ts b/src/core/workspace/__tests__/WorkspaceResolver.test.ts new file mode 100644 index 00000000..f339447b --- /dev/null +++ b/src/core/workspace/__tests__/WorkspaceResolver.test.ts @@ -0,0 +1,206 @@ +/** + * Unit tests for WorkspaceResolver + * These tests ensure behavior preservation during refactoring + */ + +import { expect } from "chai" +import { afterEach, beforeEach, describe, it } from "mocha" +import * as path from "path" +import * as sinon from "sinon" +import { Logger } from "../../../services/logging/Logger" +import { WorkspaceResolver } from "../WorkspaceResolver" +import { VcsType, WorkspaceRoot } from "../WorkspaceRoot" + +describe("WorkspaceResolver", () => { + let resolver: WorkspaceResolver + let loggerStub: sinon.SinonStub + let originalEnv: string | undefined + + beforeEach(() => { + resolver = new WorkspaceResolver() + loggerStub = sinon.stub(Logger, "debug") + originalEnv = process.env.MULTI_ROOT_TRACE + }) + + afterEach(() => { + loggerStub.restore() + process.env.MULTI_ROOT_TRACE = originalEnv + resolver.clearUsageStats() + }) + + describe("resolveWorkspacePath - Single Root Mode", () => { + const testCwd = "/test/workspace" + const testRelativePath = "src/file.ts" + const expectedAbsolutePath = path.resolve(testCwd, testRelativePath) + + it("should resolve path without context", () => { + const result = resolver.resolveWorkspacePath(testCwd, testRelativePath) + expect(result).to.equal(expectedAbsolutePath) + }) + + it("should resolve path with context and track usage", () => { + const context = "TestComponent" + const result = resolver.resolveWorkspacePath(testCwd, testRelativePath, context) + + expect(result).to.equal(expectedAbsolutePath) + + // Verify usage tracking + const usageStats = resolver.getUsageStats() + expect(usageStats.has(context)).to.be.true + + const stats = usageStats.get(context)! + expect(stats.count).to.equal(1) + expect(stats.examples).to.include(testRelativePath) + }) + + it("should track multiple calls to same context", () => { + const context = "TestComponent" + + resolver.resolveWorkspacePath(testCwd, "file1.ts", context) + resolver.resolveWorkspacePath(testCwd, "file2.ts", context) + resolver.resolveWorkspacePath(testCwd, "file1.ts", context) // duplicate + + const usageStats = resolver.getUsageStats() + const stats = usageStats.get(context)! + + expect(stats.count).to.equal(3) + expect(stats.examples).to.have.length(2) // no duplicates in examples + expect(stats.examples).to.include("file1.ts") + expect(stats.examples).to.include("file2.ts") + }) + + it("should not log when tracing is disabled", () => { + process.env.MULTI_ROOT_TRACE = "false" + process.env.NODE_ENV = "production" + + resolver.resolveWorkspacePath(testCwd, testRelativePath, "TestComponent") + + expect(loggerStub.called).to.be.false + }) + + it("should handle absolute paths correctly", () => { + const absolutePath = "/absolute/path/file.ts" + const result = resolver.resolveWorkspacePath(testCwd, absolutePath) + + expect(result).to.equal(path.resolve(testCwd, absolutePath)) + }) + + it("should handle empty relative path", () => { + const result = resolver.resolveWorkspacePath(testCwd, "") + expect(result).to.equal(path.resolve(testCwd)) + }) + + it("should handle relative paths with .. navigation", () => { + const relativePath = "../other/file.ts" + const result = resolver.resolveWorkspacePath(testCwd, relativePath) + expect(result).to.equal(path.resolve(testCwd, relativePath)) + }) + }) + + describe("resolveWorkspacePath - Multi Root Mode", () => { + const workspaceRoots: WorkspaceRoot[] = [ + { path: "/workspace/primary", name: "primary", vcs: VcsType.Git }, + { path: "/workspace/secondary", name: "secondary", vcs: VcsType.Git }, + ] + + it("should handle absolute paths in multi-root mode", () => { + const absolutePath = "/workspace/primary/src/file.ts" + const result = resolver.resolveWorkspacePath(workspaceRoots, absolutePath) + + expect(result).to.be.an("object") + expect((result as any).absolutePath).to.equal(absolutePath) + expect((result as any).root).to.equal(workspaceRoots[0]) + }) + + it("should fallback to primary root for unmatched absolute paths", () => { + const absolutePath = "/other/path/file.ts" + const result = resolver.resolveWorkspacePath(workspaceRoots, absolutePath) + + expect(result).to.be.an("object") + expect((result as any).absolutePath).to.equal(absolutePath) + expect((result as any).root).to.equal(workspaceRoots[0]) + }) + + it("should resolve relative paths against primary root", () => { + const relativePath = "src/file.ts" + const result = resolver.resolveWorkspacePath(workspaceRoots, relativePath) + + expect(result).to.be.an("object") + expect((result as any).absolutePath).to.equal(path.resolve(workspaceRoots[0].path, relativePath)) + expect((result as any).root).to.equal(workspaceRoots[0]) + }) + + it("should handle empty workspace roots array", () => { + // This should throw an error or handle gracefully + expect(() => { + resolver.resolveWorkspacePath([], "src/file.ts") + }).to.throw() + }) + }) + + describe("getBasename", () => { + const testFilePath = "/path/to/file.ts" + const expectedBasename = "file.ts" + + it("should return basename without context", () => { + const result = resolver.getBasename(testFilePath) + expect(result).to.equal(expectedBasename) + }) + + it("should return basename with context and track usage", () => { + const context = "TestComponent" + const result = resolver.getBasename(testFilePath, context) + + expect(result).to.equal(expectedBasename) + + // Verify usage tracking + const usageStats = resolver.getUsageStats() + expect(usageStats.has(context)).to.be.true + + const stats = usageStats.get(context)! + expect(stats.count).to.equal(1) + expect(stats.examples).to.include(testFilePath) + }) + }) + + describe("Usage Statistics Management", () => { + it("should track usage statistics correctly", () => { + resolver.resolveWorkspacePath("/test", "file1.ts", "Component1") + resolver.resolveWorkspacePath("/test", "file2.ts", "Component1") + resolver.getBasename("/test/file3.ts", "Component2") + + const usageStats = resolver.getUsageStats() + expect(usageStats.size).to.equal(2) + + const component1Stats = usageStats.get("Component1")! + expect(component1Stats.count).to.equal(2) + expect(component1Stats.examples).to.have.length(2) + + const component2Stats = usageStats.get("Component2")! + expect(component2Stats.count).to.equal(1) + expect(component2Stats.examples).to.have.length(1) + }) + }) + + describe("Edge Cases", () => { + it("should handle null/undefined inputs gracefully", () => { + // These should not throw + expect(() => resolver.resolveWorkspacePath("/test", "")).to.not.throw() + expect(() => resolver.getBasename("")).to.not.throw() + }) + + it("should handle special characters in paths", () => { + const specialPath = "src/file with spaces & symbols!.ts" + const result = resolver.resolveWorkspacePath("/test", specialPath, "Component") + + expect(result).to.equal(path.resolve("/test", specialPath)) + }) + + it("should handle very long paths", () => { + const longPath = "a/".repeat(100) + "file.ts" + const result = resolver.resolveWorkspacePath("/test", longPath, "Component") + + expect(result).to.equal(path.resolve("/test", longPath)) + }) + }) +}) diff --git a/src/core/workspace/index.ts b/src/core/workspace/index.ts new file mode 100644 index 00000000..2619c594 --- /dev/null +++ b/src/core/workspace/index.ts @@ -0,0 +1,18 @@ +/** + * Workspace module exports for multi-workspace support + */ + +export { + getWorkspaceBasename, + isWorkspaceTraceEnabled, + resolveWorkspacePath, + WorkspaceResolver, + workspaceResolver, +} from "@core/workspace/WorkspaceResolver" +export type { WorkspaceRoot } from "@core/workspace/WorkspaceRoot" +export { VcsType } from "@core/workspace/WorkspaceRoot" +export type { WorkspaceContext } from "@core/workspace/WorkspaceRootManager" +export { createLegacyWorkspaceRoot, WorkspaceRootManager } from "@core/workspace/WorkspaceRootManager" + +// Re-export convenience function at module level for easier imports +// Usage: import { resolveWorkspacePath } from "@core/workspace" diff --git a/src/integrations/dify/dify-integration.ts b/src/integrations/dify/dify-integration.ts index 9fbe7b0d..ace4d3e3 100644 --- a/src/integrations/dify/dify-integration.ts +++ b/src/integrations/dify/dify-integration.ts @@ -1,3 +1,4 @@ +import { workspaceResolver } from "@core/workspace" import { DifyHandler } from "../../core/api/providers/dify" /** @@ -252,14 +253,13 @@ export function createDifyIntegration( */ export async function prepareClineFilesForDify(files: string[]): Promise> { const fs = await import("fs") - const path = await import("path") const fileData: Array<{ name: string; content: Buffer }> = [] for (const filePath of files) { try { const content = fs.readFileSync(filePath) - const name = path.basename(filePath) + const name = workspaceResolver.getBasename(filePath, "DifyIntegration.prepareClineFilesForDify") fileData.push({ name, content }) } catch (error) { console.error(`Failed to read file ${filePath}:`, error) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 1e86be87..dd1c1108 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -1,10 +1,10 @@ import { formatResponse } from "@core/prompts/responses" +import { workspaceResolver } from "@core/workspace" import { createDirectoriesForFile } from "@utils/fs" import { getCwd } from "@utils/path" import * as diff from "diff" import * as fs from "fs/promises" import * as iconv from "iconv-lite" -import * as path from "path" import { HostProvider } from "@/hosts/host-provider" import { diagnosticsToProblemsString, getNewDiagnostics } from "@/integrations/diagnostics" import { DiagnosticSeverity, FileDiagnostics } from "@/shared/proto/index.cline" @@ -29,7 +29,9 @@ export abstract class DiffViewProvider { public async open(relPath: string): Promise { this.isEditing = true this.relPath = relPath - this.absolutePath = path.resolve(await getCwd(), relPath) + const cwd = await getCwd() + const absolutePathResolved = workspaceResolver.resolveWorkspacePath(cwd, relPath, "DiffViewProvider.open.absolutePath") + this.absolutePath = typeof absolutePathResolved === "string" ? absolutePathResolved : absolutePathResolved.absolutePath const fileExists = this.editType === "modify" // if the file is already open, ensure it's not dirty before getting its contents diff --git a/src/services/glob/list-files.ts b/src/services/glob/list-files.ts index f67d5c44..e5aac1e9 100644 --- a/src/services/glob/list-files.ts +++ b/src/services/glob/list-files.ts @@ -1,3 +1,4 @@ +import { workspaceResolver } from "@core/workspace" import { arePathsEqual } from "@utils/path" import { globby, Options } from "globby" import * as os from "os" @@ -39,7 +40,7 @@ function isRestrictedPath(absolutePath: string): boolean { } function isTargetingHiddenDirectory(absolutePath: string): boolean { - const dirName = path.basename(absolutePath) + const dirName = workspaceResolver.getBasename(absolutePath, "Services.glob.isTargetingHiddenDirectory") return dirName.startsWith(".") } @@ -57,7 +58,8 @@ function buildIgnorePatterns(absolutePath: string): string[] { } export async function listFiles(dirPath: string, recursive: boolean, limit: number): Promise<[string[], boolean]> { - const absolutePath = path.resolve(dirPath) + const absolutePathResult = workspaceResolver.resolveWorkspacePath(dirPath, "", "Services.glob.listFiles") + const absolutePath = typeof absolutePathResult === "string" ? absolutePathResult : absolutePathResult.absolutePath // Do not allow listing files in root or home directory if (isRestrictedPath(absolutePath)) { diff --git a/src/services/ripgrep/index.ts b/src/services/ripgrep/index.ts index fd14e165..f6b21c9a 100644 --- a/src/services/ripgrep/index.ts +++ b/src/services/ripgrep/index.ts @@ -1,4 +1,5 @@ import { ClineIgnoreController } from "@core/ignore/ClineIgnoreController" +import { workspaceResolver } from "@core/workspace" import { fileExistsAtPath } from "@utils/fs" import * as childProcess from "child_process" import * as path from "path" @@ -63,7 +64,12 @@ const MAX_RESULTS = 300 export async function getBinPath(vscodeAppRoot: string): Promise { const checkPath = async (pkgFolder: string) => { - const fullPath = path.join(vscodeAppRoot, pkgFolder, binName) + const fullPathResult = workspaceResolver.resolveWorkspacePath( + vscodeAppRoot, + path.join(pkgFolder, binName), + "Services.ripgrep.getBinPath", + ) + const fullPath = typeof fullPathResult === "string" ? fullPathResult : fullPathResult.absolutePath return (await fileExistsAtPath(fullPath)) ? fullPath : undefined } diff --git a/src/utils/fs.ts b/src/utils/fs.ts index 9ddedc11..864d82c7 100644 --- a/src/utils/fs.ts +++ b/src/utils/fs.ts @@ -1,3 +1,4 @@ +import { workspaceResolver } from "@core/workspace" import fs from "fs/promises" import * as path from "path" @@ -116,7 +117,16 @@ export const readDirectory = async (directoryPath: string, excludedPaths: string .readdir(directoryPath, { withFileTypes: true, recursive: true }) .then((entries) => entries.filter((entry) => !OS_GENERATED_FILES.includes(entry.name))) .then((entries) => entries.filter((entry) => entry.isFile())) - .then((files) => files.map((file) => path.resolve(file.parentPath, file.name))) + .then((files) => + files.map((file) => { + const resolvedPath = workspaceResolver.resolveWorkspacePath( + file.parentPath, + file.name, + "Utils.fs.readDirectory", + ) + return typeof resolvedPath === "string" ? resolvedPath : resolvedPath.absolutePath + }), + ) .then((filePaths) => filePaths.filter((filePath) => { if (excludedPaths.length === 0) { diff --git a/src/utils/path.ts b/src/utils/path.ts index 4205efa6..bb26d34d 100644 --- a/src/utils/path.ts +++ b/src/utils/path.ts @@ -1,3 +1,4 @@ +import { workspaceResolver } from "@core/workspace" import os from "os" import * as path from "path" import { HostProvider } from "@/hosts/host-provider" @@ -82,13 +83,15 @@ function normalizePath(p: string): string { export function getReadablePath(cwd: string, relPath?: string): string { relPath = relPath || "" // path.resolve is flexible in that it will resolve relative paths like '../../' to the cwd and even ignore the cwd if the relPath is actually an absolute path - const absolutePath = path.resolve(cwd, relPath) + const absolutePathResult = workspaceResolver.resolveWorkspacePath(cwd, relPath, "Utils.path.getReadablePath") + const absolutePath = typeof absolutePathResult === "string" ? absolutePathResult : absolutePathResult.absolutePath if (arePathsEqual(cwd, getDesktopDir())) { // User opened vscode without a workspace, so cwd is the Desktop. Show the full absolute path to keep the user aware of where files are being created return absolutePath.toPosix() } if (arePathsEqual(path.normalize(absolutePath), path.normalize(cwd))) { - return path.basename(absolutePath).toPosix() + const basenameResult = workspaceResolver.getBasename(absolutePath, "Utils.path.getReadablePath") + return basenameResult.toPosix() } else { // show the relative path to the cwd const normalizedRelPath = path.relative(cwd, absolutePath) @@ -108,7 +111,8 @@ export async function getCwd(defaultCwd = ""): Promise { } export function getDesktopDir() { - return path.join(os.homedir(), "Desktop") + const desktopResult = workspaceResolver.resolveWorkspacePath(os.homedir(), "Desktop", "Utils.path.getDesktopDir") + return typeof desktopResult === "string" ? desktopResult : desktopResult.absolutePath } // Returns the workspace path of the file in the current editor. @@ -131,7 +135,12 @@ export async function getWorkspacePath(defaultCwd = ""): Promise { export async function isLocatedInWorkspace(pathToCheck: string = ""): Promise { const workspacePaths = (await HostProvider.workspace.getWorkspacePaths({})).paths for (const workspacePath of workspacePaths) { - const resolvedPath = path.resolve(workspacePath, pathToCheck) + const resolvedPathResult = workspaceResolver.resolveWorkspacePath( + workspacePath, + pathToCheck, + "Utils.path.isLocatedInWorkspace", + ) + const resolvedPath = typeof resolvedPathResult === "string" ? resolvedPathResult : resolvedPathResult.absolutePath if (isLocatedInPath(workspacePath, resolvedPath)) { return true } @@ -149,7 +158,12 @@ export function isLocatedInPath(dirPath: string, pathToCheck: string): boolean { return pathToCheck.startsWith(dirPath) } - const relativePath = path.relative(path.resolve(dirPath), path.resolve(pathToCheck)) + const resolvedDirResult = workspaceResolver.resolveWorkspacePath(dirPath, "", "Utils.path.isLocatedInPath") + const resolvedDir = typeof resolvedDirResult === "string" ? resolvedDirResult : resolvedDirResult.absolutePath + const resolvedCheckResult = workspaceResolver.resolveWorkspacePath(pathToCheck, "", "Utils.path.isLocatedInPath") + const resolvedCheck = typeof resolvedCheckResult === "string" ? resolvedCheckResult : resolvedCheckResult.absolutePath + + const relativePath = path.relative(resolvedDir, resolvedCheck) if (relativePath.startsWith("..")) { return false } diff --git a/src/utils/storage.ts b/src/utils/storage.ts index 53315b2b..1d9fe2ef 100644 --- a/src/utils/storage.ts +++ b/src/utils/storage.ts @@ -1,5 +1,5 @@ +import { workspaceResolver } from "@core/workspace" import getFolderSize from "get-folder-size" -import path from "path" /** * Gets the total size of tasks and checkpoints directories @@ -7,8 +7,15 @@ import path from "path" * @returns The total size in bytes, or null if calculation fails */ export async function getTotalTasksSize(storagePath: string): Promise { - const tasksDir = path.join(storagePath, "tasks") - const checkpointsDir = path.join(storagePath, "checkpoints") + const tasksDirResult = workspaceResolver.resolveWorkspacePath(storagePath, "tasks", "Utils.storage.getTotalTasksSize") + const checkpointsDirResult = workspaceResolver.resolveWorkspacePath( + storagePath, + "checkpoints", + "Utils.storage.getTotalTasksSize", + ) + + const tasksDir = typeof tasksDirResult === "string" ? tasksDirResult : tasksDirResult.absolutePath + const checkpointsDir = typeof checkpointsDirResult === "string" ? checkpointsDirResult : checkpointsDirResult.absolutePath try { const tasksSize = await getFolderSize.loose(tasksDir) diff --git a/tsconfig.json b/tsconfig.json index de177221..cf99bf67 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -27,6 +27,9 @@ "@/*": [ "src/*" ], + "@api/*": [ + "src/core/api/*" + ], "@core/*": [ "src/core/*" ],