Elffuss BraidHub

kikocis/continue public

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