Elffuss BraidHub

kikocis/continue public

main · 15.7 KiBRawPermalink
1import { describe, expect, it } from "vitest";
2import {
3 ContextItemId,
4 ContextItemWithId,
5 RuleWithSource,
6 UserChatMessage,
7} from "../..";
8import {
9 getApplicableRules,
10 shouldApplyRule,
11} from "./getSystemMessageWithRules";
12import { RulePolicies } from "./types";
13
14describe("Rule colocation glob matching", () => {
15 // This test file demonstrates the expected behavior after our fix
16
17 it("should restrict rules by their directory when no globs specified", () => {
18 // Rule in a nested directory with no globs - should only apply to files in that directory
19 const componentRule: RuleWithSource = {
20 name: "Components Rule",
21 rule: "Use functional components with hooks",
22 source: "rules-block",
23 ruleFile: "src/components/rules.md",
24 // No explicit globs - should only apply to files in src/components/ directory
25 };
26
27 // Files in the same directory - should match
28 const matchingFiles = [
29 "src/components/Button.tsx",
30 "src/components/Form.jsx",
31 ];
32 expect(shouldApplyRule(componentRule, matchingFiles)).toBe(true);
33
34 // Files outside the directory - should NOT match
35 const nonMatchingFiles = ["src/utils/helpers.ts", "src/redux/slice.ts"];
36 expect(shouldApplyRule(componentRule, nonMatchingFiles)).toBe(false);
37 });
38
39 it("should combine directory restriction with explicit globs", () => {
40 // Rule with explicit globs in a nested directory
41 const tsxComponentRule: RuleWithSource = {
42 name: "TSX Components Rule",
43 rule: "Use TypeScript with React components",
44 globs: "**/*.tsx", // Only .tsx files
45 source: "rules-block",
46 ruleFile: "src/components/rules.md",
47 // Should only apply to .tsx files in src/components/ directory
48 };
49
50 // TSX files in the same directory - should match
51 const matchingFiles = [
52 "src/components/Button.tsx",
53 "src/components/Form.tsx",
54 ];
55 expect(shouldApplyRule(tsxComponentRule, matchingFiles)).toBe(true);
56
57 // Non-TSX files in the same directory - should NOT match
58 const nonMatchingExtension = ["src/components/OldButton.jsx"];
59 expect(shouldApplyRule(tsxComponentRule, nonMatchingExtension)).toBe(false);
60
61 // TSX files outside the directory - should NOT match
62 const nonMatchingDir = ["src/pages/Home.tsx", "src/App.tsx"];
63 expect(shouldApplyRule(tsxComponentRule, nonMatchingDir)).toBe(false);
64 });
65
66 it("should apply root-level rules to all files", () => {
67 // Rule at the root level
68 const rootRule: RuleWithSource = {
69 name: "Root Rule",
70 rule: "Follow project standards",
71 source: "rules-block",
72 ruleFile: "/path/to/repo/.continue/rules.md",
73 // No restriction, should apply to all files
74 };
75
76 // Files in various directories - should all match
77 const files = [
78 "src/components/Button.tsx",
79 "src/redux/slice.ts",
80 "src/utils/helpers.ts",
81 ];
82 expect(shouldApplyRule(rootRule, files)).toBe(true);
83 });
84
85 it("should respect alwaysApply override regardless of directory", () => {
86 // Rule with alwaysApply: true
87 const alwaysApplyRule: RuleWithSource = {
88 name: "Always Apply Rule",
89 rule: "Follow these guidelines always",
90 alwaysApply: true,
91 source: "rules-block",
92 ruleFile: "src/specific/rules.md",
93 // Should apply to all files regardless of directory
94 };
95
96 // Files in various directories - should all match due to alwaysApply: true
97 const files = [
98 "src/components/Button.tsx",
99 "src/redux/slice.ts",
100 "src/utils/helpers.ts",
101 ];
102 expect(shouldApplyRule(alwaysApplyRule, files)).toBe(true);
103
104 // Rule with alwaysApply: false and no globs
105 const neverApplyRule: RuleWithSource = {
106 name: "Never Apply Rule",
107 rule: "This rule should never apply",
108 alwaysApply: false,
109 source: "rules-block",
110 ruleFile: "src/specific/rules.md",
111 // Should never apply since alwaysApply is false and there are no globs
112 };
113
114 expect(shouldApplyRule(neverApplyRule, files)).toBe(false);
115 });
116
117 it("should support complex directory + glob combinations", () => {
118 // Rule with complex glob pattern in a nested directory
119 const testExclusionRule: RuleWithSource = {
120 name: "Test Exclusion Rule",
121 rule: "Apply to TS files but not test files",
122 globs: ["**/*.ts", "!**/*.test.ts", "!**/*.spec.ts"],
123 source: "rules-block",
124 ruleFile: "src/utils/rules.md",
125 // Should only apply to non-test TS files in src/utils/
126 };
127
128 // Regular TS file in utils - should match
129 expect(shouldApplyRule(testExclusionRule, ["src/utils/helpers.ts"])).toBe(
130 true,
131 );
132
133 // Test TS file in utils - should NOT match due to negative glob
134 expect(
135 shouldApplyRule(testExclusionRule, ["src/utils/helpers.test.ts"]),
136 ).toBe(false);
137
138 // Regular TS file outside utils - should NOT match due to directory restriction
139 expect(shouldApplyRule(testExclusionRule, ["src/models/user.ts"])).toBe(
140 false,
141 );
142 });
143});
144
145describe("Rule policies", () => {
146 const componentRule: RuleWithSource = {
147 name: "Components Rule",
148 rule: "Use functional components with hooks",
149 source: "rules-block",
150 ruleFile: "src/components/rules.md",
151 };
152
153 const testFiles = ["src/components/Button.tsx"];
154 const nonMatchingFiles = ["src/utils/helpers.ts"];
155
156 it("should never apply rules with 'off' policy regardless of file paths", () => {
157 const rulePolicies: RulePolicies = {
158 "Components Rule": "off",
159 };
160
161 // Should not apply even to matching files
162 expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(false);
163
164 // Rule with alwaysApply: true should still be overridden by 'off' policy
165 const alwaysApplyRule: RuleWithSource = {
166 name: "Always Apply Rule",
167 rule: "This rule would normally always apply",
168 alwaysApply: true,
169 source: "rules-block",
170 ruleFile: "src/components/rules.md",
171 };
172
173 const offPolicies: RulePolicies = {
174 "Always Apply Rule": "off",
175 };
176
177 expect(shouldApplyRule(alwaysApplyRule, testFiles, offPolicies)).toBe(
178 false,
179 );
180 });
181
182 it("should apply 'on' policy rules based on normal matching logic", () => {
183 const rulePolicies: RulePolicies = {
184 "Components Rule": "on",
185 };
186
187 // Should apply to matching files
188 expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true);
189
190 // Should not apply to non-matching files
191 expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe(
192 false,
193 );
194 });
195
196 it("should use default behavior when no policy is specified", () => {
197 // Empty policies object should use default behavior
198 const rulePolicies: RulePolicies = {};
199
200 // Should apply to matching files
201 expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true);
202
203 // Should not apply to non-matching files
204 expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe(
205 false,
206 );
207 });
208
209 it("should handle policy interaction with global rules", () => {
210 // Root level rule which would normally apply globally
211 const rootRule: RuleWithSource = {
212 name: "Root Rule",
213 rule: "Follow project standards",
214 source: "rules-block",
215 ruleFile: "/my/project/.continue/rules.md",
216 };
217
218 // Off policy should override even global rules
219 const offPolicies: RulePolicies = {
220 "Root Rule": "off",
221 };
222
223 expect(shouldApplyRule(rootRule, testFiles, offPolicies)).toBe(false);
224
225 // On policy should maintain global rule behavior
226 const onPolicies: RulePolicies = {
227 "Root Rule": "on",
228 };
229
230 expect(shouldApplyRule(rootRule, testFiles, onPolicies)).toBe(true);
231 });
232
233 it("should prioritize 'off' policy over alwaysApply and directory restrictions", () => {
234 // Create rule with multiple matching criteria
235 const complexRule: RuleWithSource = {
236 name: "Complex Rule",
237 rule: "This rule has complex matching logic",
238 alwaysApply: true,
239 globs: "**/*.ts",
240 source: "rules-block",
241 ruleFile: "src/utils/rules.md",
242 };
243
244 // Off policy should win over everything
245 const offPolicies: RulePolicies = {
246 "Complex Rule": "off",
247 };
248
249 // Even with matching files and alwaysApply: true, off policy wins
250 expect(
251 shouldApplyRule(complexRule, ["src/utils/test.ts"], offPolicies),
252 ).toBe(false);
253 });
254});
255
256describe("Content pattern matching", () => {
257 it("should apply rules when file content matches pattern", () => {
258 // Rule with pattern to match React component files
259 const reactComponentRule: RuleWithSource = {
260 name: "React Component Rule",
261 rule: "Follow React component standards",
262 regex: "export (function|const) \\w+.*\\(",
263 source: "rules-block",
264 ruleFile: "src/components/rules.md",
265 };
266
267 // File that matches the pattern
268 const filePath = "src/components/Button.tsx";
269 const fileContents = {
270 [filePath]:
271 "export function Button() { return <button>Click me</button> }",
272 };
273
274 expect(
275 shouldApplyRule(reactComponentRule, [filePath], {}, fileContents),
276 ).toBe(true);
277
278 // File that doesn't match the pattern
279 const nonMatchingContents = {
280 [filePath]:
281 "import React from 'react'; // Just an import, not a component",
282 };
283
284 expect(
285 shouldApplyRule(reactComponentRule, [filePath], {}, nonMatchingContents),
286 ).toBe(false);
287 });
288
289 it("should support multiple regex regex as an array", () => {
290 // Rule with multiple regex
291 const multiPatternRule: RuleWithSource = {
292 name: "Multi-Pattern Rule",
293 rule: "Apply to functions or classes",
294 regex: ["function\\s+\\w+", "class\\s+\\w+"],
295 source: "rules-block",
296 ruleFile: "src/utils/rules.md",
297 };
298
299 const filePath = "src/utils/helper.ts";
300
301 // Content with function - should match
302 const functionContent = {
303 [filePath]: "function formatDate(date) { return date.toISOString(); }",
304 };
305 expect(
306 shouldApplyRule(multiPatternRule, [filePath], {}, functionContent),
307 ).toBe(true);
308
309 // Content with class - should match
310 const classContent = {
311 [filePath]:
312 "class DateFormatter { format(date) { return date.toISOString(); } }",
313 };
314 expect(
315 shouldApplyRule(multiPatternRule, [filePath], {}, classContent),
316 ).toBe(true);
317
318 // Content with neither - should not match
319 const nonMatchingContent = {
320 [filePath]: "const PI = 3.14159;",
321 };
322 expect(
323 shouldApplyRule(multiPatternRule, [filePath], {}, nonMatchingContent),
324 ).toBe(false);
325 });
326
327 it("should apply rules based on both globs and regex when both are specified", () => {
328 // Rule with both glob and pattern restrictions
329 const typescriptClassRule: RuleWithSource = {
330 name: "TypeScript Class Rule",
331 rule: "Follow class standards in TypeScript",
332 globs: "**/*.ts",
333 regex: "class\\s+\\w+",
334 source: "rules-block",
335 ruleFile: "src/models/rules.md",
336 };
337
338 const tsFilePath = "src/models/User.ts";
339 const jsFilePath = "src/models/Product.js";
340
341 // TypeScript file with class - should match
342 const tsClassContent = {
343 [tsFilePath]: "export class User { constructor(public name: string) {} }",
344 };
345 expect(
346 shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsClassContent),
347 ).toBe(true);
348
349 // TypeScript file without class - should not match
350 const tsNonClassContent = {
351 [tsFilePath]: "export const createUser = (name: string) => ({ name });",
352 };
353 expect(
354 shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsNonClassContent),
355 ).toBe(false);
356
357 // JavaScript file with class - should not match due to glob
358 const jsClassContent = {
359 [jsFilePath]:
360 "export class Product { constructor(name) { this.name = name; } }",
361 };
362 expect(
363 shouldApplyRule(typescriptClassRule, [jsFilePath], {}, jsClassContent),
364 ).toBe(false);
365 });
366
367 it("should extract file content from messages for pattern matching", () => {
368 // Rule with pattern
369 const arrowFunctionRule: RuleWithSource = {
370 name: "Arrow Function Rule",
371 rule: "Use arrow functions for better this binding",
372 regex: "const\\s+\\w+\\s*=\\s*\\(",
373 source: "rules-block",
374 ruleFile: "src/utils/rules.md",
375 };
376
377 // Message with code block containing a matching pattern
378 const messageWithArrowFn: UserChatMessage = {
379 role: "user",
380 content:
381 "Can you check this code?\n```typescript src/utils/formatter.ts\nconst format = (date) => {\n return date.toISOString();\n};\n```",
382 };
383
384 // Create context item to match the file in the message
385 const contextItem: ContextItemWithId = {
386 id: { providerTitle: "file", itemId: "formatter" } as ContextItemId,
387 uri: { type: "file", value: "src/utils/formatter.ts" },
388 content: "const format = (date) => {\n return date.toISOString();\n};",
389 name: "formatter.ts",
390 description: "Utility formatter",
391 };
392
393 // Should match the pattern
394 const applicableRules = getApplicableRules(
395 messageWithArrowFn,
396 [arrowFunctionRule],
397 [contextItem],
398 );
399
400 expect(applicableRules).toHaveLength(1);
401 expect(applicableRules[0].name).toBe("Arrow Function Rule");
402
403 // Message with code block that doesn't match the pattern
404 const messageWithoutArrowFn: UserChatMessage = {
405 role: "user",
406 content:
407 "Can you check this code?\n```typescript src/utils/formatter.ts\nfunction format(date) {\n return date.toISOString();\n}\n```",
408 };
409
410 // Context item with non-matching content
411 const nonMatchingContextItem: ContextItemWithId = {
412 id: { providerTitle: "file", itemId: "formatter2" } as ContextItemId,
413 uri: { type: "file", value: "src/utils/formatter.ts" },
414 content: "function format(date) {\n return date.toISOString();\n}",
415 name: "formatter.ts",
416 description: "Utility formatter",
417 };
418
419 // Should not match the pattern
420 const nonApplicableRules = getApplicableRules(
421 messageWithoutArrowFn,
422 [arrowFunctionRule],
423 [nonMatchingContextItem],
424 );
425
426 expect(nonApplicableRules).toHaveLength(0);
427 });
428
429 it("should handle invalid regex regex gracefully", () => {
430 // Rule with invalid regex pattern
431 const invalidRegexRule: RuleWithSource = {
432 name: "Invalid Regex Rule",
433 rule: "This rule has an invalid regex pattern",
434 regex: "([unclosed parenthesis",
435 source: "rules-block",
436 ruleFile: "src/utils/rules.md",
437 };
438
439 const filePath = "src/utils/helper.ts";
440 const fileContents = {
441 [filePath]: "function helper() { return true; }",
442 };
443
444 // Should not throw an error but gracefully not apply the rule
445 expect(
446 shouldApplyRule(invalidRegexRule, [filePath], {}, fileContents),
447 ).toBe(false);
448 });
449
450 it("should respect directory restrictions for pattern rules", () => {
451 // Rule with pattern in a nested directory
452 const nestedPatternRule: RuleWithSource = {
453 name: "Nested Pattern Rule",
454 rule: "Apply only to model files with interfaces",
455 regex: "interface\\s+\\w+",
456 source: "rules-block",
457 ruleFile: "src/models/rules.md",
458 };
459
460 // File in the correct directory with matching content
461 const modelFilePath = "src/models/User.ts";
462 const modelContents = {
463 [modelFilePath]: "export interface User { id: string; name: string; }",
464 };
465 expect(
466 shouldApplyRule(nestedPatternRule, [modelFilePath], {}, modelContents),
467 ).toBe(true);
468
469 // File outside the directory with matching content - should not match
470 const utilFilePath = "src/utils/types.ts";
471 const utilContents = {
472 [utilFilePath]:
473 "export interface Config { apiUrl: string; timeout: number; }",
474 };
475 expect(
476 shouldApplyRule(nestedPatternRule, [utilFilePath], {}, utilContents),
477 ).toBe(false);
478 });
479});