Elffuss BraidHub

kikocis/continue public

main · 11.0 KiBRawPermalink
1import { minimatch } from "minimatch";
2import {
3 ContextItemWithId,
4 RuleWithSource,
5 ToolResultChatMessage,
6 UserChatMessage,
7} from "../..";
8import { renderChatMessage } from "../../util/messageContent";
9import { getCleanUriPath } from "../../util/uri";
10import { extractContentFromCodeBlock } from "../utils/extractContentFromCodeBlocks";
11import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
12import { RulePolicies } from "./types";
13
14/**
15 * Checks if a path matches any of the provided globs
16 * Supports negative patterns with ! prefix
17 */
18const matchesGlobs = (
19 filePath: string,
20 globs: string | string[] | undefined,
21): boolean => {
22 if (!globs) return true;
23
24 // Handle single string glob
25 if (typeof globs === "string") {
26 if (globs.startsWith("!")) {
27 // Negative pattern - return false if it matches
28 return !minimatch(filePath, globs.substring(1));
29 }
30 return minimatch(filePath, globs);
31 }
32
33 // Handle array of globs
34 if (Array.isArray(globs)) {
35 // Split into positive and negative patterns
36 const positivePatterns = globs.filter((g) => !g.startsWith("!"));
37 const negativePatterns = globs
38 .filter((g) => g.startsWith("!"))
39 .map((g) => g.substring(1)); // Remove ! prefix
40
41 // If there are no positive patterns, the file matches unless it matches a negative pattern
42 if (positivePatterns.length === 0) {
43 return !negativePatterns.some((pattern) => minimatch(filePath, pattern));
44 }
45
46 // File must match at least one positive pattern AND not match any negative patterns
47 return (
48 positivePatterns.some((pattern) => minimatch(filePath, pattern)) &&
49 !negativePatterns.some((pattern) => minimatch(filePath, pattern))
50 );
51 }
52
53 return false;
54};
55
56/**
57 * Checks if file content matches any of the provided regex regex
58 *
59 * @param fileContent - The content of the file to check
60 * @param regex - A single regex pattern string or array of regex pattern strings
61 * @returns true if the content matches any pattern (or if no regex is provided), false otherwise
62 */
63const contentMatchesRegex = (
64 fileContent: string,
65 regex: string | string[],
66): boolean => {
67 // Handle single string pattern
68 if (typeof regex === "string") {
69 try {
70 const expression = new RegExp(regex);
71 return expression.test(fileContent);
72 } catch (e) {
73 console.error(`Invalid regex pattern: ${regex}`, e);
74 return false;
75 }
76 }
77
78 // Handle array of regex
79 if (Array.isArray(regex)) {
80 if (regex.length === 0) return true;
81
82 // Content must match at least one pattern
83 return regex.some((pattern) => {
84 try {
85 const regex = new RegExp(pattern);
86 return regex.test(fileContent);
87 } catch (e) {
88 console.error(`Invalid regex pattern: ${pattern}`, e);
89 return false;
90 }
91 });
92 }
93
94 return false;
95};
96
97/**
98 * Determines if a file path is within a specific directory or its subdirectories
99 *
100 * @param filePath - The file path to check
101 * @param directoryPath - The directory path to check against
102 * @returns true if the file is in the directory or subdirectory, false otherwise
103 */
104const isFileInDirectory = (
105 filePath: string,
106 directoryPath: string,
107): boolean => {
108 // Normalize paths for consistent comparison
109 let normalizedFilePath = filePath.replace(/\\/g, "/");
110 let normalizedDirPath = directoryPath.replace(/\\/g, "/");
111
112 // Strip the file:// protocol if present
113 normalizedFilePath = normalizedFilePath.replace(/^file:\/\//, "");
114 normalizedDirPath = normalizedDirPath.replace(/^file:\/\//, "");
115
116 // Extract the last parts of the paths for comparison
117 // This allows matching relative paths with absolute paths
118 // e.g., "nested-folder/file.py" should match "/path/to/nested-folder/"
119 const dirPathParts = normalizedDirPath.split("/");
120
121 // Get the directory name (last part of the directory path)
122 const dirName = dirPathParts[dirPathParts.length - 1];
123
124 // Check if the file path contains this directory followed by a slash
125 // This is a simple check to see if the file might be in this directory
126 const containsDir = normalizedFilePath.includes(`${dirName}/`);
127
128 return containsDir;
129};
130
131/**
132 * Checks if a rule is a root-level rule (.continue directory or no file path)
133 */
134const isRootLevelRule = (rule: RuleWithSource): boolean => {
135 return !rule.ruleFile || rule.ruleFile.includes(".continue/"); // ruleFile path is absolute - hence we need to check for it in between
136};
137
138/**
139 * Determines if a rule should be considered global and always applied
140 * This includes rules with alwaysApply: true OR root-level rules with no globs
141 */
142const isGlobalRule = (rule: RuleWithSource): boolean => {
143 // Rules with alwaysApply: true are always global
144 if (rule.alwaysApply === true) {
145 return true;
146 }
147
148 // Root-level rules with no globs or regex are implicitly global
149 if (
150 isRootLevelRule(rule) &&
151 !rule.globs &&
152 !rule.regex &&
153 rule.alwaysApply !== false
154 ) {
155 return true;
156 }
157
158 return false;
159};
160
161const checkGlobsAndRegex = ({
162 rule,
163 filePaths,
164 fileContents,
165}: {
166 rule: RuleWithSource;
167 filePaths: string[];
168 fileContents: Record<string, string>;
169}) => {
170 const matchingFiles = rule.globs
171 ? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs))
172 : filePaths;
173
174 // If no files match the globs, don't apply the rule
175 if (matchingFiles.length === 0) {
176 return false;
177 }
178
179 // Now check for pattern matches in file contents if regex are specified
180 if (rule.regex) {
181 // Check if any of the matching files also match the content regex
182 return matchingFiles.some((filePath) => {
183 const content = fileContents[filePath];
184 // If we don't have the content, we can't check regex
185 if (!content) return false;
186 return contentMatchesRegex(content, rule.regex!);
187 });
188 }
189
190 // If we have no regex or if we couldn't check regex (no content),
191 // just go with the glob matches
192 return matchingFiles.length > 0;
193};
194
195/**
196 * Determines if a rule should be applied based on its properties and file matching
197 *
198 * @param rule - The rule to check
199 * @param filePaths - Array of file paths to check against the rule's globs
200 * @param fileContents - Map of file paths to their contents for pattern matching
201 * @param rulePolicies - Optional policies that can override normal rule behavior
202 * @returns true if the rule should be applied, false otherwise
203 */
204export const shouldApplyRule = (
205 rule: RuleWithSource,
206 filePaths: string[],
207 rulePolicies: RulePolicies = {},
208 fileContents: Record<string, string> = {},
209): boolean => {
210 const policy = rulePolicies[rule.name || ""];
211
212 // Never apply if policy is "off"
213 if (policy === "off") {
214 return false;
215 }
216
217 // If it's a global rule, always apply it regardless of file paths
218 if (isGlobalRule(rule)) {
219 return true;
220 }
221
222 // If there are no file paths to check and we've made it here:
223 // - We've already handled global rules above
224 // - Don't apply other rules since we have no files to match against
225 if (filePaths.length === 0) {
226 return false;
227 }
228
229 // Check if this is a root-level rule (in .continue directory or no file path)
230 const isRootRule = isRootLevelRule(rule);
231
232 // For non-root rules, we need to check if any files are in the rule's directory
233 if (!isRootRule && rule.ruleFile) {
234 const ruleDirectory = getCleanUriPath(rule.ruleFile);
235 const lastSlashIndex = ruleDirectory.lastIndexOf("/");
236 const ruleDirPath =
237 lastSlashIndex !== -1 ? ruleDirectory.substring(0, lastSlashIndex) : "";
238
239 // Filter to only files in this directory or its subdirectories
240 const filesInRuleDirectory = filePaths.filter((filePath) =>
241 isFileInDirectory(filePath, ruleDirPath),
242 );
243
244 return checkGlobsAndRegex({
245 filePaths: filesInRuleDirectory,
246 fileContents,
247 rule,
248 });
249 }
250
251 // If alwaysApply is explicitly false, we need to check globs and/or regex
252 if (
253 rule.alwaysApply === false &&
254 rule.globs === undefined &&
255 rule.regex === undefined
256 ) {
257 return false;
258 }
259
260 return checkGlobsAndRegex({
261 filePaths,
262 fileContents,
263 rule,
264 });
265};
266
267/**
268 * Filters rules that apply to the given message and/or context items
269 *
270 * @param userMessage - The user or tool message to check for file paths in code blocks
271 * @param rules - The list of rules to filter
272 * @param contextItems - Context items to check for file paths
273 * @returns List of applicable rules
274 */
275export const getApplicableRules = (
276 userMessage: UserChatMessage | ToolResultChatMessage | undefined,
277 rules: RuleWithSource[],
278 contextItems: ContextItemWithId[],
279 rulePolicies: RulePolicies = {},
280): RuleWithSource[] => {
281 // Get file paths from message and context for rule matching
282 const filePathsFromMessage = userMessage
283 ? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
284 : [];
285
286 // Extract file paths from context items
287 const filePathsFromContextItems = contextItems
288 .filter((item) => item.uri?.type === "file" && item.uri?.value)
289 .map((item) => item.uri!.value);
290
291 // Combine file paths from both sources
292 const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
293
294 // Create a map of file paths to their contents for pattern matching
295 const fileContents: Record<string, string> = {};
296
297 // Extract contents from context items with file URIs
298 contextItems.forEach((item) => {
299 if (item.uri?.type === "file" && item.uri?.value) {
300 fileContents[item.uri.value] = item.content;
301 }
302 });
303
304 // Extract contents from code blocks in the message for paths that don't have content yet
305 if (userMessage) {
306 const messageContent = renderChatMessage(userMessage);
307 filePathsFromMessage.forEach((path) => {
308 // Only extract content if we don't already have it from context items
309 if (!fileContents[path]) {
310 const blockContent = extractContentFromCodeBlock(messageContent, path);
311 if (blockContent) {
312 fileContents[path] = blockContent;
313 }
314 }
315 });
316 }
317
318 // Apply shouldApplyRule to all rules - this will handle global rules, rule policies,
319 // and path matching in a consistent way
320 const applicableRules = rules.filter((rule) =>
321 shouldApplyRule(rule, allFilePaths, rulePolicies, fileContents),
322 );
323
324 return applicableRules;
325};
326
327export function getRuleId(rule: RuleWithSource): string {
328 return rule.slug ?? rule.ruleFile ?? rule.name ?? rule.source;
329}
330
331export const getSystemMessageWithRules = ({
332 baseSystemMessage,
333 userMessage,
334 availableRules,
335 contextItems,
336 rulePolicies = {},
337}: {
338 baseSystemMessage?: string;
339 userMessage: UserChatMessage | ToolResultChatMessage | undefined;
340 availableRules: RuleWithSource[];
341 contextItems: ContextItemWithId[];
342 rulePolicies?: RulePolicies;
343}): {
344 systemMessage: string;
345 appliedRules: RuleWithSource[];
346} => {
347 const appliedRules = getApplicableRules(
348 userMessage,
349 availableRules,
350 contextItems,
351 rulePolicies,
352 );
353 let systemMessage = baseSystemMessage ?? "";
354
355 for (const rule of appliedRules) {
356 if (systemMessage) {
357 systemMessage += "\n\n";
358 }
359 systemMessage += rule.rule;
360 }
361
362 return {
363 systemMessage,
364 appliedRules,
365 };
366};