Elffuss BraidHub

kikocis/continue public

68dbf00e2c2f · 8.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 { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
11import { RulePolicies } from "./types";
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 !rule.ruleFile || rule.ruleFile.startsWith(".continue/");
94};
95
96/**
97 * Determines if a rule should be considered global and always applied
98 * This includes rules with alwaysApply: true OR root-level rules with no globs
99 */
100const isGlobalRule = (rule: RuleWithSource): boolean => {
101 // Rules with alwaysApply: true are always global
102 if (rule.alwaysApply === true) {
103 return true;
104 }
105
106 // Root-level rules with no globs are implicitly global
107 if (isRootLevelRule(rule) && !rule.globs && rule.alwaysApply !== false) {
108 return true;
109 }
110
111 return false;
112};
113
114/**
115 * Determines if a rule should be applied based on its alwaysApply property and file path matching
116 *
117 * @param rule - The rule to check
118 * @param filePaths - Array of file paths to check against the rule's globs
119 * @returns true if the rule should be applied, false otherwise
120 */
121export const shouldApplyRule = (
122 rule: RuleWithSource,
123 filePaths: string[],
124 rulePolicies: RulePolicies = {},
125): boolean => {
126 const policy = rulePolicies[rule.name || ""];
127
128 // Never apply if policy is "off"
129 if (policy === "off") {
130 return false;
131 }
132
133 // If it's a global rule, always apply it regardless of file paths
134 if (isGlobalRule(rule)) {
135 return true;
136 }
137
138 // If there are no file paths to check and we've made it here:
139 // - We've already handled global rules above
140 // - Don't apply other rules since we have no files to match against
141 if (filePaths.length === 0) {
142 return false;
143 }
144
145 // Check if this is a root-level rule (in .continue directory or no file path)
146 const isRootRule = isRootLevelRule(rule);
147
148 // For non-root rules, we need to check if any files are in the rule's directory
149 if (!isRootRule && rule.ruleFile) {
150 const ruleDirectory = getCleanUriPath(rule.ruleFile);
151 const lastSlashIndex = ruleDirectory.lastIndexOf("/");
152 const ruleDirPath =
153 lastSlashIndex !== -1 ? ruleDirectory.substring(0, lastSlashIndex) : "";
154
155 // Filter to only files in this directory or its subdirectories
156 const filesInRuleDirectory = filePaths.filter((filePath) =>
157 isFileInDirectory(filePath, ruleDirPath),
158 );
159
160 // If no files are in this directory, don't apply the rule
161 if (filesInRuleDirectory.length === 0) {
162 return false;
163 }
164
165 // If we have globs, check if any files in this directory match them
166 if (rule.globs) {
167 return filesInRuleDirectory.some((filePath) =>
168 matchesGlobs(filePath, rule.globs),
169 );
170 }
171
172 // No globs but files are in this directory, so apply the rule
173 return true;
174 }
175
176 // For root-level rules:
177
178 // If alwaysApply is explicitly false, only apply if there are globs AND they match
179 if (rule.alwaysApply === false) {
180 if (!rule.globs) {
181 return false;
182 }
183 return filePaths.some((path) => matchesGlobs(path, rule.globs));
184 }
185
186 // Default behavior for root rules with globs:
187 // - Only apply if they match the globs
188 if (rule.globs) {
189 return filePaths.some((path) => matchesGlobs(path, rule.globs));
190 }
191
192 // This point should not be reached as we've handled all cases above
193 return false;
194};
195
196/**
197 * Filters rules that apply to the given message and/or context items
198 *
199 * @param userMessage - The user or tool message to check for file paths in code blocks
200 * @param rules - The list of rules to filter
201 * @param contextItems - Context items to check for file paths
202 * @returns List of applicable rules
203 */
204export const getApplicableRules = (
205 userMessage: UserChatMessage | ToolResultChatMessage | undefined,
206 rules: RuleWithSource[],
207 contextItems: ContextItemWithId[],
208 rulePolicies: RulePolicies = {},
209): RuleWithSource[] => {
210 // Get file paths from message and context for rule matching
211 const filePathsFromMessage = userMessage
212 ? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
213 : [];
214
215 // Extract file paths from context items
216 const filePathsFromContextItems = contextItems
217 .filter((item) => item.uri?.type === "file" && item.uri?.value)
218 .map((item) => item.uri!.value);
219
220 // Combine file paths from both sources
221 const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
222
223 // Apply shouldApplyRule to all rules - this will handle global rules, rule policies,
224 // and path matching in a consistent way
225 const applicableRules = rules.filter((rule) =>
226 shouldApplyRule(rule, allFilePaths, rulePolicies),
227 );
228
229 return applicableRules;
230};
231
232export const getSystemMessageWithRules = ({
233 baseSystemMessage,
234 userMessage,
235 rules,
236 contextItems,
237 rulePolicies = {},
238}: {
239 baseSystemMessage?: string;
240 userMessage: UserChatMessage | ToolResultChatMessage | undefined;
241 rules: RuleWithSource[];
242 contextItems: ContextItemWithId[];
243 rulePolicies?: RulePolicies;
244}) => {
245 const applicableRules = getApplicableRules(
246 userMessage,
247 rules,
248 contextItems,
249 rulePolicies,
250 );
251 let systemMessage = baseSystemMessage ?? "";
252
253 for (const rule of applicableRules) {
254 systemMessage += `\n\n${rule.rule}`;
255 }
256
257 return systemMessage;
258};