fix: type errors / formatting

This commit is contained in:
Tomasz Stefaniak 2025-06-09 16:07:27 -07:00
parent a7f6f99edc
commit 9dba4730b9
6 changed files with 315 additions and 284 deletions

View file

@ -1,153 +1,161 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { loadCodebaseRules } from './loadCodebaseRules';
import { walkDirs } from '../../indexing/walkDir';
import { IDE } from '../..';
import { convertMarkdownRuleToContinueRule } from './parseMarkdownRule';
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { IDE } from "../..";
import { walkDirs } from "../../indexing/walkDir";
import { loadCodebaseRules } from "./loadCodebaseRules";
import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
// Mock dependencies
vi.mock('../../indexing/walkDir', () => ({
vi.mock("../../indexing/walkDir", () => ({
walkDirs: vi.fn(),
}));
vi.mock('./parseMarkdownRule', () => ({
vi.mock("./parseMarkdownRule", () => ({
convertMarkdownRuleToContinueRule: vi.fn(),
}));
describe('loadCodebaseRules', () => {
// Mock IDE
describe("loadCodebaseRules", () => {
// Mock IDE with properly typed mock functions
const mockIde = {
readFile: vi.fn(),
readFile: vi.fn() as unknown as IDE["readFile"] & {
mockImplementation: Function;
},
} as unknown as IDE;
// Setup test files
const mockFiles = [
'src/rules.md',
'src/redux/rules.md',
'src/components/rules.md',
'src/utils/helper.ts', // Non-rules file
'.continue/rules.md', // This should also be loaded
"src/rules.md",
"src/redux/rules.md",
"src/components/rules.md",
"src/utils/helper.ts", // Non-rules file
".continue/rules.md", // This should also be loaded
];
// Mock rule content
const mockRuleContent = {
'src/rules.md': '# General Rules\nFollow coding standards',
'src/redux/rules.md': '---\nglobs: "**/*.{ts,tsx}"\n---\n# Redux Rules\nUse Redux Toolkit',
'src/components/rules.md': '---\nglobs: ["**/*.tsx", "**/*.jsx"]\n---\n# Component Rules\nUse functional components',
'.continue/rules.md': '# Global Rules\nFollow project guidelines',
const mockRuleContent: Record<string, string> = {
"src/rules.md": "# General Rules\nFollow coding standards",
"src/redux/rules.md":
'---\nglobs: "**/*.{ts,tsx}"\n---\n# Redux Rules\nUse Redux Toolkit',
"src/components/rules.md":
'---\nglobs: ["**/*.tsx", "**/*.jsx"]\n---\n# Component Rules\nUse functional components',
".continue/rules.md": "# Global Rules\nFollow project guidelines",
};
// Mock converted rules
const mockConvertedRules = {
'src/rules.md': {
name: 'General Rules',
rule: 'Follow coding standards',
source: 'rules-block',
ruleFile: 'src/rules.md',
const mockConvertedRules: Record<string, any> = {
"src/rules.md": {
name: "General Rules",
rule: "Follow coding standards",
source: "rules-block",
ruleFile: "src/rules.md",
},
'src/redux/rules.md': {
name: 'Redux Rules',
rule: 'Use Redux Toolkit',
globs: '**/*.{ts,tsx}',
source: 'rules-block',
ruleFile: 'src/redux/rules.md',
"src/redux/rules.md": {
name: "Redux Rules",
rule: "Use Redux Toolkit",
globs: "**/*.{ts,tsx}",
source: "rules-block",
ruleFile: "src/redux/rules.md",
},
'src/components/rules.md': {
name: 'Component Rules',
rule: 'Use functional components',
globs: ['**/*.tsx', '**/*.jsx'],
source: 'rules-block',
ruleFile: 'src/components/rules.md',
"src/components/rules.md": {
name: "Component Rules",
rule: "Use functional components",
globs: ["**/*.tsx", "**/*.jsx"],
source: "rules-block",
ruleFile: "src/components/rules.md",
},
'.continue/rules.md': {
name: 'Global Rules',
rule: 'Follow project guidelines',
source: 'rules-block',
ruleFile: '.continue/rules.md',
".continue/rules.md": {
name: "Global Rules",
rule: "Follow project guidelines",
source: "rules-block",
ruleFile: ".continue/rules.md",
},
};
beforeEach(() => {
// Setup mocks
vi.resetAllMocks();
// Mock walkDirs to return our test files
(walkDirs as any).mockResolvedValue(mockFiles);
// Mock readFile to return content based on path
mockIde.readFile.mockImplementation((path: string) => {
return Promise.resolve(mockRuleContent[path] || '');
(mockIde.readFile as any).mockImplementation((path: string) => {
return Promise.resolve(mockRuleContent[path] || "");
});
// Mock convertMarkdownRuleToContinueRule to return converted rules
(convertMarkdownRuleToContinueRule as any).mockImplementation((path: string, content: string) => {
return mockConvertedRules[path];
});
(convertMarkdownRuleToContinueRule as any).mockImplementation(
(path: string, content: string) => {
return mockConvertedRules[path];
},
);
});
afterEach(() => {
vi.resetAllMocks();
});
it('should load rules from all rules.md files in the workspace', async () => {
it("should load rules from all rules.md files in the workspace", async () => {
const { rules, errors } = await loadCodebaseRules(mockIde);
// Should find all rules.md files
expect(walkDirs).toHaveBeenCalledWith(mockIde);
// Should read all rules.md files
expect(mockIde.readFile).toHaveBeenCalledTimes(4);
expect(mockIde.readFile).toHaveBeenCalledWith('src/rules.md');
expect(mockIde.readFile).toHaveBeenCalledWith('src/redux/rules.md');
expect(mockIde.readFile).toHaveBeenCalledWith('src/components/rules.md');
expect(mockIde.readFile).toHaveBeenCalledWith('.continue/rules.md');
expect(mockIde.readFile).toHaveBeenCalledWith("src/rules.md");
expect(mockIde.readFile).toHaveBeenCalledWith("src/redux/rules.md");
expect(mockIde.readFile).toHaveBeenCalledWith("src/components/rules.md");
expect(mockIde.readFile).toHaveBeenCalledWith(".continue/rules.md");
// Should convert all rules
expect(convertMarkdownRuleToContinueRule).toHaveBeenCalledTimes(4);
// Should return all rules
expect(rules).toHaveLength(4);
expect(rules).toContainEqual(mockConvertedRules['src/rules.md']);
expect(rules).toContainEqual(mockConvertedRules['src/redux/rules.md']);
expect(rules).toContainEqual(mockConvertedRules['src/components/rules.md']);
expect(rules).toContainEqual(mockConvertedRules['.continue/rules.md']);
expect(rules).toContainEqual(mockConvertedRules["src/rules.md"]);
expect(rules).toContainEqual(mockConvertedRules["src/redux/rules.md"]);
expect(rules).toContainEqual(mockConvertedRules["src/components/rules.md"]);
expect(rules).toContainEqual(mockConvertedRules[".continue/rules.md"]);
// Should not have errors
expect(errors).toHaveLength(0);
});
it('should handle errors when reading a rule file', async () => {
it("should handle errors when reading a rule file", async () => {
// Setup mock to throw for a specific file
mockIde.readFile.mockImplementation((path: string) => {
if (path === 'src/redux/rules.md') {
return Promise.reject(new Error('Failed to read file'));
(mockIde.readFile as any).mockImplementation((path: string) => {
if (path === "src/redux/rules.md") {
return Promise.reject(new Error("Failed to read file"));
}
return Promise.resolve(mockRuleContent[path] || '');
return Promise.resolve(mockRuleContent[path] || "");
});
const { rules, errors } = await loadCodebaseRules(mockIde);
// Should still return other rules
expect(rules).toHaveLength(3);
expect(rules).toContainEqual(mockConvertedRules['src/rules.md']);
expect(rules).toContainEqual(mockConvertedRules['src/components/rules.md']);
expect(rules).toContainEqual(mockConvertedRules['.continue/rules.md']);
expect(rules).toContainEqual(mockConvertedRules["src/rules.md"]);
expect(rules).toContainEqual(mockConvertedRules["src/components/rules.md"]);
expect(rules).toContainEqual(mockConvertedRules[".continue/rules.md"]);
// Should have one error
expect(errors).toHaveLength(1);
expect(errors[0].message).toContain('Failed to parse colocated rule file src/redux/rules.md');
expect(errors[0].message).toContain(
"Failed to parse colocated rule file src/redux/rules.md",
);
});
it('should handle errors when walkDirs fails', async () => {
it("should handle errors when walkDirs fails", async () => {
// Setup mock to throw
(walkDirs as any).mockRejectedValue(new Error('Failed to walk directories'));
(walkDirs as any).mockRejectedValue(
new Error("Failed to walk directories"),
);
const { rules, errors } = await loadCodebaseRules(mockIde);
// Should return no rules
expect(rules).toHaveLength(0);
// Should have one error
expect(errors).toHaveLength(1);
expect(errors[0].message).toContain('Error loading colocated rule files');
expect(errors[0].message).toContain("Error loading colocated rule files");
});
});
});

View file

@ -1,6 +1,12 @@
import path from "path";
import { beforeEach, describe, expect, it } from "vitest";
import { ContextItemWithId, RuleWithSource, UserChatMessage } from "../..";
import {
ContextItemId,
ContextItemWithId,
RuleWithSource,
UserChatMessage,
} from "../..";
import { getApplicableRules } from "../../llm/rules/getSystemMessageWithRules";
describe("Rule Colocation Application", () => {
@ -68,86 +74,82 @@ describe("Rule Colocation Application", () => {
beforeEach(() => {
// Setup user messages with different code blocks
userMessageWithComponentFile = {
id: "1",
role: "user",
content:
"Can you help me with this component file?\n```tsx src/components/Button.tsx\nexport const Button = () => {...}\n```",
createdAt: new Date().toISOString(),
};
userMessageWithComponentJsxFile = {
id: "1b",
role: "user",
content:
"Can you help me with this JSX component file?\n```jsx src/components/OldButton.jsx\nexport const OldButton = () => {...}\n```",
createdAt: new Date().toISOString(),
};
userMessageWithReduxFile = {
id: "2",
role: "user",
content:
'Can you help with this redux slice?\n```ts src/redux/userSlice.ts\nimport { createSlice } from "@reduxjs/toolkit";\n```',
createdAt: new Date().toISOString(),
};
userMessageWithRootFile = {
id: "3",
role: "user",
content:
"Can you help with this utility file?\n```ts src/utils/helpers.ts\nexport const formatDate = (date) => {...}\n```",
createdAt: new Date().toISOString(),
};
userMessageWithApiUtilFile = {
id: "4",
role: "user",
content:
"Can you help with this API utility file?\n```ts src/utils/api/requests.ts\nexport const fetchData = () => {...}\n```",
createdAt: new Date().toISOString(),
};
// Setup context items
componentTsxContextItem = {
id: "context1",
id: { providerTitle: "file", itemId: "context1" } as ContextItemId,
uri: { type: "file", value: "src/components/Button.tsx" },
content: "export const Button = () => {...}",
retrievedAt: new Date().toISOString(),
name: "Button.tsx",
description: "Component file",
};
componentJsxContextItem = {
id: "context1b",
id: { providerTitle: "file", itemId: "context1b" } as ContextItemId,
uri: { type: "file", value: "src/components/OldButton.jsx" },
content: "export const OldButton = () => {...}",
retrievedAt: new Date().toISOString(),
name: "OldButton.jsx",
description: "Component file",
};
reduxContextItem = {
id: "context2",
id: { providerTitle: "file", itemId: "context2" } as ContextItemId,
uri: { type: "file", value: "src/redux/userSlice.ts" },
content: 'import { createSlice } from "@reduxjs/toolkit";',
retrievedAt: new Date().toISOString(),
name: "userSlice.ts",
description: "Redux slice",
};
rootContextItem = {
id: "context3",
id: { providerTitle: "file", itemId: "context3" } as ContextItemId,
uri: { type: "file", value: "src/utils/helpers.ts" },
content: "export const formatDate = (date) => {...}",
retrievedAt: new Date().toISOString(),
name: "helpers.ts",
description: "Utility file",
};
apiUtilContextItem = {
id: "context4",
id: { providerTitle: "file", itemId: "context4" } as ContextItemId,
uri: { type: "file", value: "src/utils/api/requests.ts" },
content: "export const fetchData = () => {...}",
retrievedAt: new Date().toISOString(),
name: "requests.ts",
description: "API utility file",
};
otherUtilContextItem = {
id: "context5",
id: { providerTitle: "file", itemId: "context5" } as ContextItemId,
uri: { type: "file", value: "src/utils/format.ts" },
content: "export const formatCurrency = (amount) => {...}",
retrievedAt: new Date().toISOString(),
name: "format.ts",
description: "Formatting utility",
};
});
@ -338,17 +340,19 @@ describe("Rule Colocation Application", () => {
// Create context items for different files
const modelFileContext: ContextItemWithId = {
id: "models1",
id: { providerTitle: "file", itemId: "models1" } as ContextItemId,
uri: { type: "file", value: "src/models/user.ts" },
content: "export interface User {...}",
retrievedAt: new Date().toISOString(),
name: "user.ts",
description: "User model",
};
const serviceFileContext: ContextItemWithId = {
id: "services1",
id: { providerTitle: "file", itemId: "services1" } as ContextItemId,
uri: { type: "file", value: "src/services/auth.ts" },
content: "export const login = () => {...}",
retrievedAt: new Date().toISOString(),
name: "auth.ts",
description: "Auth service",
};
// Test with model file - should apply only the models rule

View file

@ -1,137 +1,139 @@
import { describe, expect, it } from 'vitest';
import { ContextItemWithId, RuleWithSource, UserChatMessage } from '../..';
import { getApplicableRules } from './getSystemMessageWithRules';
import { describe, expect, it } from "vitest";
import {
ContextItemId,
ContextItemWithId,
RuleWithSource,
UserChatMessage,
} from "../..";
import { getApplicableRules } from "./getSystemMessageWithRules";
describe('Rule application with alwaysApply', () => {
describe("Rule application with alwaysApply", () => {
// Create an always-apply rule
const alwaysApplyRule: RuleWithSource = {
name: 'Always Apply Rule',
rule: 'This rule should always be applied',
name: "Always Apply Rule",
rule: "This rule should always be applied",
alwaysApply: true,
source: 'rules-block',
ruleFile: '.continue/always-apply.md',
};
// Create a colocated rule in a nested directory
const nestedDirRule: RuleWithSource = {
name: 'Nested Directory Rule',
rule: 'This rule applies to files in the nested directory',
source: 'rules-block',
ruleFile: 'nested-folder/rules.md',
source: "rules-block",
ruleFile: ".continue/always-apply.md",
};
it('should apply alwaysApply rules even with no file references', () => {
// Create a colocated rule in a nested directory
const nestedDirRule: RuleWithSource = {
name: "Nested Directory Rule",
rule: "This rule applies to files in the nested directory",
source: "rules-block",
ruleFile: "nested-folder/rules.md",
};
it("should apply alwaysApply rules even with no file references", () => {
// Message with no code blocks or file references
const simpleMessage: UserChatMessage = {
id: '1',
role: 'user',
content: 'Can you help me understand how this works?',
createdAt: new Date().toISOString(),
role: "user",
content: "Can you help me understand how this works?",
};
// Apply rules with no context items
const applicableRules = getApplicableRules(
simpleMessage,
simpleMessage,
[alwaysApplyRule, nestedDirRule],
[]
[],
);
// The always apply rule should be included regardless of context
expect(applicableRules).toHaveLength(1);
expect(applicableRules.map(r => r.name)).toContain('Always Apply Rule');
expect(applicableRules.map(r => r.name)).not.toContain('Nested Directory Rule');
expect(applicableRules.map((r) => r.name)).toContain("Always Apply Rule");
expect(applicableRules.map((r) => r.name)).not.toContain(
"Nested Directory Rule",
);
});
it('should apply nested directory rules to files in that directory', () => {
it("should apply nested directory rules to files in that directory", () => {
// Context with a file in the nested directory
const nestedFileContext: ContextItemWithId = {
id: 'context1',
uri: { type: 'file', value: 'nested-folder/example.ts' },
content: 'export const example = () => {...}',
retrievedAt: new Date().toISOString(),
id: { providerTitle: "file", itemId: "context1" } as ContextItemId,
uri: { type: "file", value: "nested-folder/example.ts" },
content: "export const example = () => {...}",
name: "example.ts",
description: "Example file",
};
// Apply rules with file context in nested directory
const applicableRules = getApplicableRules(
undefined, // No message needed
[alwaysApplyRule, nestedDirRule],
[nestedFileContext]
[nestedFileContext],
);
// Both rules should apply
expect(applicableRules).toHaveLength(2);
expect(applicableRules.map(r => r.name)).toContain('Always Apply Rule');
expect(applicableRules.map(r => r.name)).toContain('Nested Directory Rule');
expect(applicableRules.map((r) => r.name)).toContain("Always Apply Rule");
expect(applicableRules.map((r) => r.name)).toContain(
"Nested Directory Rule",
);
});
it('should NOT apply nested directory rules to files outside that directory', () => {
it("should NOT apply nested directory rules to files outside that directory", () => {
// Context with a file outside the nested directory
const outsideFileContext: ContextItemWithId = {
id: 'context2',
uri: { type: 'file', value: 'src/utils/helper.ts' },
content: 'export const helper = () => {...}',
retrievedAt: new Date().toISOString(),
id: { providerTitle: "file", itemId: "context2" } as ContextItemId,
uri: { type: "file", value: "src/utils/helper.ts" },
content: "export const helper = () => {...}",
name: "helper.ts",
description: "Helper utility",
};
// Apply rules with file context outside nested directory
const applicableRules = getApplicableRules(
undefined, // No message needed
[alwaysApplyRule, nestedDirRule],
[outsideFileContext]
[outsideFileContext],
);
// Only the always apply rule should be included
expect(applicableRules).toHaveLength(1);
expect(applicableRules.map(r => r.name)).toContain('Always Apply Rule');
expect(applicableRules.map(r => r.name)).not.toContain('Nested Directory Rule');
expect(applicableRules.map((r) => r.name)).toContain("Always Apply Rule");
expect(applicableRules.map((r) => r.name)).not.toContain(
"Nested Directory Rule",
);
});
it('should correctly apply rules when a file is mentioned in a message', () => {
it("should correctly apply rules when a file is mentioned in a message", () => {
// Message with a file reference
const messageWithFile: UserChatMessage = {
id: '3',
role: 'user',
content: 'Can you help with this file?\n```ts nested-folder/example.ts\nexport const example = () => {...}\n```',
createdAt: new Date().toISOString(),
role: "user",
content:
"Can you help with this file?\n```ts nested-folder/example.ts\nexport const example = () => {...}\n```",
};
// Apply rules with a message containing a file reference
const applicableRules = getApplicableRules(
messageWithFile,
[alwaysApplyRule, nestedDirRule],
[]
[],
);
// Both rules should apply
expect(applicableRules).toHaveLength(2);
expect(applicableRules.map(r => r.name)).toContain('Always Apply Rule');
expect(applicableRules.map(r => r.name)).toContain('Nested Directory Rule');
expect(applicableRules.map((r) => r.name)).toContain("Always Apply Rule");
expect(applicableRules.map((r) => r.name)).toContain(
"Nested Directory Rule",
);
});
it('should always apply rules with alwaysApply regardless of message or context', () => {
it("should always apply rules with alwaysApply regardless of message or context", () => {
// Test with no message or context
let applicableRules = getApplicableRules(
undefined,
[alwaysApplyRule],
[]
);
let applicableRules = getApplicableRules(undefined, [alwaysApplyRule], []);
expect(applicableRules).toHaveLength(1);
expect(applicableRules.map(r => r.name)).toContain('Always Apply Rule');
expect(applicableRules.map((r) => r.name)).toContain("Always Apply Rule");
// Test with message but no file references and no context
const simpleMessage: UserChatMessage = {
id: '4',
role: 'user',
content: 'Hello, can you help me?',
createdAt: new Date().toISOString(),
role: "user",
content: "Hello, can you help me?",
};
applicableRules = getApplicableRules(
simpleMessage,
[alwaysApplyRule],
[]
);
applicableRules = getApplicableRules(simpleMessage, [alwaysApplyRule], []);
expect(applicableRules).toHaveLength(1);
expect(applicableRules.map(r => r.name)).toContain('Always Apply Rule');
expect(applicableRules.map((r) => r.name)).toContain("Always Apply Rule");
});
});
});

View file

@ -1,53 +1,55 @@
import { describe, expect, it } from 'vitest';
import { RuleWithSource } from '../..';
import { shouldApplyRule } from './getSystemMessageWithRules';
import { describe, expect, it } from "vitest";
import { RuleWithSource } from "../..";
import { shouldApplyRule } from "./getSystemMessageWithRules";
describe('File Path Protocol Matching', () => {
describe("File Path Protocol Matching", () => {
// Test rule with a file:// protocol in the path - simulating what happens in VSCode
const ruleWithFileProtocol: RuleWithSource = {
name: 'Rule with file:// protocol',
rule: 'This is a test rule',
source: 'rules-block',
ruleFile: 'file:///Users/user/project/nested-folder/rules.md',
name: "Rule with file:// protocol",
rule: "This is a test rule",
source: "rules-block",
ruleFile: "file:///Users/user/project/nested-folder/rules.md",
};
it('should match relative paths with file:// protocol paths', () => {
it("should match relative paths with file:// protocol paths", () => {
// This is the key test case that would have failed before:
// A relative path should match with a file:// protocol directory path
const relativePaths = ['nested-folder/example.py'];
const relativePaths = ["nested-folder/example.py"];
// Before the fix, this would have failed because the string comparison
// would be checking if 'nested-folder/example.py' starts with
// would be checking if 'nested-folder/example.py' starts with
// 'file:///Users/user/project/nested-folder/'
expect(shouldApplyRule(ruleWithFileProtocol, relativePaths)).toBe(true);
});
it('should match when directory name appears in the path', () => {
it("should match when directory name appears in the path", () => {
// Even with a more complex relative path, it should match as long as
// it contains the right directory structure
const nestedPaths = ['src/components/nested-folder/example.py'];
const nestedPaths = ["src/components/nested-folder/example.py"];
expect(shouldApplyRule(ruleWithFileProtocol, nestedPaths)).toBe(true);
});
it('should not match when directory name is not in the path', () => {
it("should not match when directory name is not in the path", () => {
// Should not match when the path doesn't contain the directory name
const unrelatedPaths = ['src/components/other-folder/example.py'];
const unrelatedPaths = ["src/components/other-folder/example.py"];
expect(shouldApplyRule(ruleWithFileProtocol, unrelatedPaths)).toBe(false);
});
it('should match absolute paths with the same protocol', () => {
it("should match absolute paths with the same protocol", () => {
// Should also work with absolute paths
const absolutePaths = ['file:///Users/user/project/nested-folder/example.py'];
const absolutePaths = [
"file:///Users/user/project/nested-folder/example.py",
];
expect(shouldApplyRule(ruleWithFileProtocol, absolutePaths)).toBe(true);
});
it('should handle mixed path types in the same call', () => {
it("should handle mixed path types in the same call", () => {
// Should handle a mix of relative and absolute paths
const mixedPaths = [
'nested-folder/example.py',
'file:///Users/user/project/nested-folder/other.py',
'src/unrelated/file.py'
"nested-folder/example.py",
"file:///Users/user/project/nested-folder/other.py",
"src/unrelated/file.py",
];
expect(shouldApplyRule(ruleWithFileProtocol, mixedPaths)).toBe(true);
});
});
});

View file

@ -1,129 +1,136 @@
import { describe, expect, it } from 'vitest';
import { ContextItemWithId, RuleWithSource, UserChatMessage } from '../..';
import { getApplicableRules } from './getSystemMessageWithRules';
import { describe, expect, it } from "vitest";
import { RuleWithSource, UserChatMessage } from "../..";
import { getApplicableRules } from "./getSystemMessageWithRules";
describe('Implicit global rules application', () => {
describe("Implicit global rules application", () => {
// Create a rule with no alwaysApply and no globs - should behave like a global rule
const implicitGlobalRule: RuleWithSource = {
name: 'Implicit Global Rule',
rule: 'This rule should be applied to all messages (implicit global)',
source: 'rules-block',
ruleFile: '.continue/global-rule.md',
name: "Implicit Global Rule",
rule: "This rule should be applied to all messages (implicit global)",
source: "rules-block",
ruleFile: ".continue/global-rule.md",
// No alwaysApply specified
// No globs specified
};
// Create a rule with explicit alwaysApply: true for comparison
const explicitGlobalRule: RuleWithSource = {
name: 'Explicit Global Rule',
rule: 'This rule should always be applied (explicit global)',
name: "Explicit Global Rule",
rule: "This rule should always be applied (explicit global)",
alwaysApply: true,
source: 'rules-block',
ruleFile: '.continue/explicit-global.md',
};
// Create a colocated rule in a nested directory
const nestedDirRule: RuleWithSource = {
name: 'Nested Directory Rule',
rule: 'This rule applies to files in the nested directory',
source: 'rules-block',
ruleFile: 'nested-folder/rules.md',
source: "rules-block",
ruleFile: ".continue/explicit-global.md",
};
it('should apply rules with no alwaysApply and no globs to all messages, even with no file references', () => {
// Create a colocated rule in a nested directory
const nestedDirRule: RuleWithSource = {
name: "Nested Directory Rule",
rule: "This rule applies to files in the nested directory",
source: "rules-block",
ruleFile: "nested-folder/rules.md",
};
it("should apply rules with no alwaysApply and no globs to all messages, even with no file references", () => {
// Message with no code blocks or file references
const simpleMessage: UserChatMessage = {
id: '1',
role: 'user',
content: 'Can you help me understand how this works?',
createdAt: new Date().toISOString(),
role: "user",
content: "Can you help me understand how this works?",
};
// Apply rules with no context items
const applicableRules = getApplicableRules(
simpleMessage,
simpleMessage,
[implicitGlobalRule, explicitGlobalRule, nestedDirRule],
[]
[],
);
// Both global rules should be included regardless of context
expect(applicableRules).toHaveLength(2);
expect(applicableRules.map(r => r.name)).toContain('Implicit Global Rule');
expect(applicableRules.map(r => r.name)).toContain('Explicit Global Rule');
expect(applicableRules.map(r => r.name)).not.toContain('Nested Directory Rule');
expect(applicableRules.map((r) => r.name)).toContain(
"Implicit Global Rule",
);
expect(applicableRules.map((r) => r.name)).toContain(
"Explicit Global Rule",
);
expect(applicableRules.map((r) => r.name)).not.toContain(
"Nested Directory Rule",
);
});
it('should treat root-level rules with no globs as global rules', () => {
it("should treat root-level rules with no globs as global rules", () => {
// Root rule with no globs
const rootNoGlobsRule: RuleWithSource = {
name: 'Root No Globs Rule',
rule: 'This is a root-level rule with no globs',
source: 'rules-block',
ruleFile: '.continue/rules.md',
name: "Root No Globs Rule",
rule: "This is a root-level rule with no globs",
source: "rules-block",
ruleFile: ".continue/rules.md",
// No alwaysApply, no globs
};
// Test with no file context
const applicableRules = getApplicableRules(
undefined,
[rootNoGlobsRule],
[]
[],
);
// Should include the rule even with no context
expect(applicableRules).toHaveLength(1);
expect(applicableRules[0].name).toBe('Root No Globs Rule');
expect(applicableRules[0].name).toBe("Root No Globs Rule");
});
it('should apply implicit global rules alongside file-specific rules', () => {
it("should apply implicit global rules alongside file-specific rules", () => {
// File-specific message
const messageWithFile: UserChatMessage = {
id: '2',
role: 'user',
content: 'Can you help with this file?\n```ts nested-folder/example.ts\nexport const example = () => {...}\n```',
createdAt: new Date().toISOString(),
role: "user",
content:
"Can you help with this file?\n```ts nested-folder/example.ts\nexport const example = () => {...}\n```",
};
// Apply all rule types together
const applicableRules = getApplicableRules(
messageWithFile,
[implicitGlobalRule, explicitGlobalRule, nestedDirRule],
[]
[],
);
// Should include all rules
expect(applicableRules).toHaveLength(3);
expect(applicableRules.map(r => r.name)).toContain('Implicit Global Rule');
expect(applicableRules.map(r => r.name)).toContain('Explicit Global Rule');
expect(applicableRules.map(r => r.name)).toContain('Nested Directory Rule');
expect(applicableRules.map((r) => r.name)).toContain(
"Implicit Global Rule",
);
expect(applicableRules.map((r) => r.name)).toContain(
"Explicit Global Rule",
);
expect(applicableRules.map((r) => r.name)).toContain(
"Nested Directory Rule",
);
});
it('should apply implicit global rules for first message without code', () => {
it("should apply implicit global rules for first message without code", () => {
// Simple first message
const firstMessage: UserChatMessage = {
id: '3',
role: 'user',
content: 'Hello, can you help me?',
createdAt: new Date().toISOString(),
role: "user",
content: "Hello, can you help me?",
};
// Assistant rules that should always apply
const assistantRule: RuleWithSource = {
name: 'Assistant Guidelines',
rule: 'SOLID Design Principles - Coding Assistant Guidelines',
source: 'rules-block',
ruleFile: '.continue/rules.md',
name: "Assistant Guidelines",
rule: "SOLID Design Principles - Coding Assistant Guidelines",
source: "rules-block",
ruleFile: ".continue/rules.md",
// No alwaysApply, no globs - should still apply
};
const applicableRules = getApplicableRules(
firstMessage,
[assistantRule],
[]
[],
);
// Should include the assistant rule even though there's no code
expect(applicableRules).toHaveLength(1);
expect(applicableRules[0].name).toBe('Assistant Guidelines');
expect(applicableRules[0].name).toBe("Assistant Guidelines");
});
});
});

View file

@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest";
import { ContextItemWithId, RuleWithSource, UserChatMessage } from "../..";
import {
ContextItemId,
ContextItemWithId,
RuleWithSource,
UserChatMessage,
} from "../..";
import { getApplicableRules } from "./getSystemMessageWithRules";
describe("Nested directory rules application", () => {
@ -23,13 +28,14 @@ describe("Nested directory rules application", () => {
it("should apply nested directory rules to files in that directory", () => {
// Create a context with a file in the nested directory
const nestedFileContext: ContextItemWithId = {
id: "nested1",
id: { providerTitle: "file", itemId: "nested1" } as ContextItemId,
uri: {
type: "file",
value: "manual-testing-sandbox/nested-folder/hellonested.py",
},
content: 'print("Hello nested")',
retrievedAt: new Date().toISOString(),
name: "hellonested.py",
description: "Nested file",
};
// Apply rules with the nested file context
@ -48,11 +54,9 @@ describe("Nested directory rules application", () => {
it("should also work with file references in messages", () => {
// Message with a file reference in the nested directory
const messageWithNestedFile: UserChatMessage = {
id: "msg1",
role: "user",
content:
'Can you explain this file?\n```python manual-testing-sandbox/nested-folder/hellonested.py\nprint("Hello nested")\n```',
createdAt: new Date().toISOString(),
};
// Apply rules with the message containing a nested file reference
@ -71,10 +75,11 @@ describe("Nested directory rules application", () => {
it("should NOT apply nested directory rules to files outside that directory", () => {
// Context with a file outside the nested directory
const outsideFileContext: ContextItemWithId = {
id: "outside1",
id: { providerTitle: "file", itemId: "outside1" } as ContextItemId,
uri: { type: "file", value: "src/utils/helper.ts" },
content: "export const helper = () => {...}",
retrievedAt: new Date().toISOString(),
name: "helper.ts",
description: "Helper file",
};
// Apply rules with file context outside nested directory
@ -112,26 +117,29 @@ describe("Nested directory rules application", () => {
// A file in src/
const srcPythonFileContext: ContextItemWithId = {
id: "python1",
id: { providerTitle: "file", itemId: "python1" } as ContextItemId,
uri: { type: "file", value: "src/pythonfile.py" },
content: 'print("Hello")',
retrievedAt: new Date().toISOString(),
name: "pythonfile.py",
description: "Python file in src",
};
// A file in utils/
const utilsPythonFileContext: ContextItemWithId = {
id: "python2",
id: { providerTitle: "file", itemId: "python2" } as ContextItemId,
uri: { type: "file", value: "utils/pythonfile.py" },
content: 'print("Hello")',
retrievedAt: new Date().toISOString(),
name: "pythonfile.py",
description: "Python file in utils",
};
// A file in manual-testing-sandbox/
const manualTestingPythonFileContext: ContextItemWithId = {
id: "python3",
id: { providerTitle: "file", itemId: "python3" } as ContextItemId,
uri: { type: "file", value: "manual-testing-sandbox/pythonfile.py" },
content: 'print("Hello")',
retrievedAt: new Date().toISOString(),
name: "pythonfile.py",
description: "Python file in manual-testing-sandbox",
};
// Apply src rule to src file - should match