Elffuss BraidHub

kikocis/continue public

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