| 1 | import { minimatch } from "minimatch"; |
| 2 | import { |
| 3 | ContextItemWithId, |
| 4 | RuleWithSource, |
| 5 | ToolResultChatMessage, |
| 6 | UserChatMessage, |
| 7 | } from "../.."; |
| 8 | import { renderChatMessage } from "../../util/messageContent"; |
| 9 | import { getCleanUriPath } from "../../util/uri"; |
| 10 | import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; |
| 11 | |
| 12 | /** |
| 13 | * Checks if a path matches any of the provided globs |
| 14 | * Supports negative patterns with ! prefix |
| 15 | */ |
| 16 | const matchesGlobs = ( |
| 17 | filePath: string, |
| 18 | globs: string | string[] | undefined, |
| 19 | ): boolean => { |
| 20 | if (!globs) return true; |
| 21 | |
| 22 | // Handle single string glob |
| 23 | if (typeof globs === "string") { |
| 24 | if (globs.startsWith("!")) { |
| 25 | // Negative pattern - return false if it matches |
| 26 | return !minimatch(filePath, globs.substring(1)); |
| 27 | } |
| 28 | return minimatch(filePath, globs); |
| 29 | } |
| 30 | |
| 31 | // Handle array of globs |
| 32 | if (Array.isArray(globs)) { |
| 33 | // Split into positive and negative patterns |
| 34 | const positivePatterns = globs.filter((g) => !g.startsWith("!")); |
| 35 | const negativePatterns = globs |
| 36 | .filter((g) => g.startsWith("!")) |
| 37 | .map((g) => g.substring(1)); // Remove ! prefix |
| 38 | |
| 39 | // If there are no positive patterns, the file matches unless it matches a negative pattern |
| 40 | if (positivePatterns.length === 0) { |
| 41 | return !negativePatterns.some((pattern) => minimatch(filePath, pattern)); |
| 42 | } |
| 43 | |
| 44 | // File must match at least one positive pattern AND not match any negative patterns |
| 45 | return ( |
| 46 | positivePatterns.some((pattern) => minimatch(filePath, pattern)) && |
| 47 | !negativePatterns.some((pattern) => minimatch(filePath, pattern)) |
| 48 | ); |
| 49 | } |
| 50 | |
| 51 | return false; |
| 52 | }; |
| 53 | |
| 54 | /** |
| 55 | * Determines if a file path is within a specific directory or its subdirectories |
| 56 | * |
| 57 | * @param filePath - The file path to check |
| 58 | * @param directoryPath - The directory path to check against |
| 59 | * @returns true if the file is in the directory or subdirectory, false otherwise |
| 60 | */ |
| 61 | const isFileInDirectory = ( |
| 62 | filePath: string, |
| 63 | directoryPath: string, |
| 64 | ): boolean => { |
| 65 | // Normalize paths for consistent comparison |
| 66 | let normalizedFilePath = filePath.replace(/\\/g, "/"); |
| 67 | let normalizedDirPath = directoryPath.replace(/\\/g, "/"); |
| 68 | |
| 69 | // Strip the file:// protocol if present |
| 70 | normalizedFilePath = normalizedFilePath.replace(/^file:\/\//, ""); |
| 71 | normalizedDirPath = normalizedDirPath.replace(/^file:\/\//, ""); |
| 72 | |
| 73 | // Extract the last parts of the paths for comparison |
| 74 | // This allows matching relative paths with absolute paths |
| 75 | // e.g., "nested-folder/file.py" should match "/path/to/nested-folder/" |
| 76 | const dirPathParts = normalizedDirPath.split("/"); |
| 77 | |
| 78 | // Get the directory name (last part of the directory path) |
| 79 | const dirName = dirPathParts[dirPathParts.length - 1]; |
| 80 | |
| 81 | // Check if the file path contains this directory followed by a slash |
| 82 | // This is a simple check to see if the file might be in this directory |
| 83 | const containsDir = normalizedFilePath.includes(`${dirName}/`); |
| 84 | |
| 85 | return containsDir; |
| 86 | }; |
| 87 | |
| 88 | /** |
| 89 | * Checks if a rule is a root-level rule (.continue directory or no file path) |
| 90 | */ |
| 91 | const isRootLevelRule = (rule: RuleWithSource): boolean => { |
| 92 | return !rule.ruleFile || rule.ruleFile.startsWith(".continue/"); |
| 93 | }; |
| 94 | |
| 95 | /** |
| 96 | * Determines if a rule should be considered global and always applied |
| 97 | * This includes rules with alwaysApply: true OR root-level rules with no globs |
| 98 | */ |
| 99 | const isGlobalRule = (rule: RuleWithSource): boolean => { |
| 100 | // Rules with alwaysApply: true are always global |
| 101 | if (rule.alwaysApply === true) { |
| 102 | return true; |
| 103 | } |
| 104 | |
| 105 | // Root-level rules with no globs are implicitly global |
| 106 | if (isRootLevelRule(rule) && !rule.globs && rule.alwaysApply !== false) { |
| 107 | return true; |
| 108 | } |
| 109 | |
| 110 | return false; |
| 111 | }; |
| 112 | |
| 113 | /** |
| 114 | * Determines if a rule should be applied based on its alwaysApply property and file path matching |
| 115 | * |
| 116 | * @param rule - The rule to check |
| 117 | * @param filePaths - Array of file paths to check against the rule's globs |
| 118 | * @returns true if the rule should be applied, false otherwise |
| 119 | */ |
| 120 | export const shouldApplyRule = ( |
| 121 | rule: RuleWithSource, |
| 122 | filePaths: string[], |
| 123 | ): boolean => { |
| 124 | // If it's a global rule, always apply it regardless of file paths |
| 125 | if (isGlobalRule(rule)) { |
| 126 | return true; |
| 127 | } |
| 128 | |
| 129 | // If there are no file paths to check: |
| 130 | // - We've already handled global rules above |
| 131 | // - Don't apply other rules since we have no files to match against |
| 132 | if (filePaths.length === 0) { |
| 133 | return false; |
| 134 | } |
| 135 | |
| 136 | // Check if this is a root-level rule (in .continue directory or no file path) |
| 137 | const isRootRule = isRootLevelRule(rule); |
| 138 | |
| 139 | // For non-root rules, we need to check if any files are in the rule's directory |
| 140 | if (!isRootRule && rule.ruleFile) { |
| 141 | const ruleDirectory = getCleanUriPath(rule.ruleFile); |
| 142 | const lastSlashIndex = ruleDirectory.lastIndexOf("/"); |
| 143 | const ruleDirPath = |
| 144 | lastSlashIndex !== -1 ? ruleDirectory.substring(0, lastSlashIndex) : ""; |
| 145 | |
| 146 | // Filter to only files in this directory or its subdirectories |
| 147 | const filesInRuleDirectory = filePaths.filter((filePath) => |
| 148 | isFileInDirectory(filePath, ruleDirPath), |
| 149 | ); |
| 150 | |
| 151 | // If no files are in this directory, don't apply the rule |
| 152 | if (filesInRuleDirectory.length === 0) { |
| 153 | return false; |
| 154 | } |
| 155 | |
| 156 | // If we have globs, check if any files in this directory match them |
| 157 | if (rule.globs) { |
| 158 | return filesInRuleDirectory.some((filePath) => |
| 159 | matchesGlobs(filePath, rule.globs), |
| 160 | ); |
| 161 | } |
| 162 | |
| 163 | // No globs but files are in this directory, so apply the rule |
| 164 | return true; |
| 165 | } |
| 166 | |
| 167 | // For root-level rules: |
| 168 | |
| 169 | // If alwaysApply is explicitly false, only apply if there are globs AND they match |
| 170 | if (rule.alwaysApply === false) { |
| 171 | if (!rule.globs) { |
| 172 | return false; |
| 173 | } |
| 174 | return filePaths.some((path) => matchesGlobs(path, rule.globs)); |
| 175 | } |
| 176 | |
| 177 | // Default behavior for root rules with globs: |
| 178 | // - Only apply if they match the globs |
| 179 | if (rule.globs) { |
| 180 | return filePaths.some((path) => matchesGlobs(path, rule.globs)); |
| 181 | } |
| 182 | |
| 183 | // This point should not be reached as we've handled all cases above |
| 184 | return false; |
| 185 | }; |
| 186 | |
| 187 | /** |
| 188 | * Filters rules that apply to the given message and/or context items |
| 189 | * |
| 190 | * @param userMessage - The user or tool message to check for file paths in code blocks |
| 191 | * @param rules - The list of rules to filter |
| 192 | * @param contextItems - Context items to check for file paths |
| 193 | * @returns List of applicable rules |
| 194 | */ |
| 195 | export const getApplicableRules = ( |
| 196 | userMessage: UserChatMessage | ToolResultChatMessage | undefined, |
| 197 | rules: RuleWithSource[], |
| 198 | contextItems: ContextItemWithId[], |
| 199 | ): RuleWithSource[] => { |
| 200 | // First, extract any global rules that should always apply |
| 201 | const globalRules = rules.filter((rule) => isGlobalRule(rule)); |
| 202 | |
| 203 | // Get file paths from message and context for regular rule matching |
| 204 | const filePathsFromMessage = userMessage |
| 205 | ? extractPathsFromCodeBlocks(renderChatMessage(userMessage)) |
| 206 | : []; |
| 207 | |
| 208 | // Extract file paths from context items |
| 209 | const filePathsFromContextItems = contextItems |
| 210 | .filter((item) => item.uri?.type === "file" && item.uri?.value) |
| 211 | .map((item) => item.uri!.value); |
| 212 | |
| 213 | // Combine file paths from both sources |
| 214 | const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems]; |
| 215 | |
| 216 | // If we have no file paths, just return the global rules |
| 217 | if (allFilePaths.length === 0) { |
| 218 | return globalRules; |
| 219 | } |
| 220 | |
| 221 | // Get rules that match file paths |
| 222 | const matchingRules = rules |
| 223 | .filter((rule) => !isGlobalRule(rule)) // Skip global rules as we've already handled them |
| 224 | .filter((rule) => shouldApplyRule(rule, allFilePaths)); |
| 225 | |
| 226 | // Combine global rules with matching rules, ensuring no duplicates |
| 227 | return [...globalRules, ...matchingRules]; |
| 228 | }; |
| 229 | |
| 230 | /** |
| 231 | * Creates a system message string with applicable rules appended |
| 232 | * |
| 233 | * @param baseSystemMessage - The base system message to start with |
| 234 | * @param userMessage - The user message to check for file paths |
| 235 | * @param rules - The list of rules to filter |
| 236 | * @param contextItems - Context items to check for file paths |
| 237 | * @returns System message with applicable rules appended |
| 238 | */ |
| 239 | export const getSystemMessageWithRules = ({ |
| 240 | baseSystemMessage, |
| 241 | userMessage, |
| 242 | rules, |
| 243 | contextItems, |
| 244 | }: { |
| 245 | baseSystemMessage?: string; |
| 246 | userMessage: UserChatMessage | ToolResultChatMessage | undefined; |
| 247 | rules: RuleWithSource[]; |
| 248 | contextItems: ContextItemWithId[]; |
| 249 | }) => { |
| 250 | const applicableRules = getApplicableRules(userMessage, rules, contextItems); |
| 251 | let systemMessage = baseSystemMessage ?? ""; |
| 252 | |
| 253 | for (const rule of applicableRules) { |
| 254 | systemMessage += `\n\n${rule.rule}`; |
| 255 | } |
| 256 | |
| 257 | return systemMessage; |
| 258 | }; |