Elffuss BraidHub

kikocis/continue public

Merge pull request #5760 from continuedev/tomasz/markdown-rules

feat: markdown rules
Changesete1bfdf0232bec45e0d33297f721ac86c9d59886357d665e081f1d9de5a218ed7
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-05-20 16:43 -07:00
CommitterGitHub <noreply@github.com> · 2025-05-20 16:43 -07:00
Parentsdc8c63430e51, bcd4eba04f14

Browse the files at this changeset

9 files changed

modified core/config/ConfigHandler.ts +2 −2
@@ -19,7 +19,7 @@
1919 import { logger } from "../util/logger.js";
2020 import {
2121 ASSISTANTS,
22- getAllDotContinueYamlFiles,
22+ getAllDotContinueDefinitionFiles,
2323 LoadAssistantFilesOptions,
2424 } from "./loadLocalAssistants.js";
2525 import LocalProfileLoader from "./profile/LocalProfileLoader.js";
@@ -284,7 +284,7 @@
284284 }
285285
286286 if (options.includeWorkspace) {
287- const assistantFiles = await getAllDotContinueYamlFiles(
287+ const assistantFiles = await getAllDotContinueDefinitionFiles(
288288 this.ide,
289289 options,
290290 ASSISTANTS,
modified core/config/loadLocalAssistants.ts +5 −5
@@ -13,7 +13,7 @@
1313 export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
1414
1515 export function isLocalAssistantFile(uri: string): boolean {
16- if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) {
16+ if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) {
1717 return false;
1818 }
1919
@@ -21,7 +21,7 @@
2121 return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
2222 }
2323
24-export async function listYamlFilesInDir(
24+async function getDefinitionFilesInDir(
2525 ide: IDE,
2626 dir: string,
2727 ): Promise<{ path: string; content: string }[]> {
@@ -41,7 +41,7 @@
4141 source: "get assistant files",
4242 });
4343 const assistantFilePaths = uris.filter(
44- (p) => p.endsWith(".yaml") || p.endsWith(".yml"),
44+ (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"),
4545 );
4646 const results = assistantFilePaths.map(async (uri) => {
4747 const content = await ide.readFile(uri); // make a try catch
@@ -86,7 +86,7 @@
8686 * This method searches in both ~/.continue and workspace .continue
8787 * for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts
8888 */
89-export async function getAllDotContinueYamlFiles(
89+export async function getAllDotContinueDefinitionFiles(
9090 ide: IDE,
9191 options: LoadAssistantFilesOptions,
9292 subDirName: string,
@@ -103,7 +103,7 @@
103103
104104 // Get all assistant files from the directories
105105 const assistantFiles = (
106- await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir)))
106+ await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir)))
107107 ).flat();
108108
109109 return await Promise.all(
added core/config/markdown/loadMarkdownRules.ts +47 −0
@@ -0,0 +1,47 @@
1+import { ConfigValidationError } from "@continuedev/config-yaml";
2+import { IDE, RuleWithSource } from "../..";
3+import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
4+import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
5+
6+/**
7+ * Loads rules from markdown files in the .continue/rules directory
8+ */
9+export async function loadMarkdownRules(ide: IDE): Promise<{
10+ rules: RuleWithSource[];
11+ errors: ConfigValidationError[];
12+}> {
13+ const errors: ConfigValidationError[] = [];
14+ const rules: RuleWithSource[] = [];
15+
16+ try {
17+ // Get all .md files from .continue/rules
18+ const markdownFiles = await getAllDotContinueDefinitionFiles(
19+ ide,
20+ { includeGlobal: true, includeWorkspace: true },
21+ "rules",
22+ );
23+
24+ // Filter to just .md files
25+ const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md"));
26+
27+ // Process each markdown file
28+ for (const file of mdFiles) {
29+ try {
30+ const rule = convertMarkdownRuleToContinueRule(file.path, file.content);
31+ rules.push(rule);
32+ } catch (e) {
33+ errors.push({
34+ fatal: false,
35+ message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`,
36+ });
37+ }
38+ }
39+ } catch (e) {
40+ errors.push({
41+ fatal: false,
42+ message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}`,
43+ });
44+ }
45+
46+ return { rules, errors };
47+}
added core/config/markdown/parseMarkdownRule.test.ts +154 −0
@@ -0,0 +1,154 @@
1+import {
2+ convertMarkdownRuleToContinueRule,
3+ parseMarkdownRule,
4+} from "./parseMarkdownRule";
5+
6+describe("parseMarkdownRule", () => {
7+ it("should correctly parse markdown with YAML frontmatter", () => {
8+ const content = `---
9+globs: "**/test/**/*.kt"
10+---
11+
12+# Test Rule
13+
14+This is a test rule.`;
15+
16+ const result = parseMarkdownRule(content);
17+ expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
18+ expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
19+ });
20+
21+ it("should handle missing frontmatter", () => {
22+ const content = `# Test Rule
23+
24+This is a test rule without frontmatter.`;
25+
26+ const result = parseMarkdownRule(content);
27+ expect(result.frontmatter).toEqual({});
28+ expect(result.markdown).toBe(content);
29+ });
30+
31+ it("should handle empty frontmatter", () => {
32+ const content = `---
33+---
34+
35+# Test Rule
36+
37+This is a test rule with empty frontmatter.`;
38+
39+ const result = parseMarkdownRule(content);
40+
41+ // Log exact strings for debugging
42+ console.log("Actual:", JSON.stringify(result.markdown));
43+ console.log(
44+ "Expected:",
45+ JSON.stringify(
46+ "# Test Rule\n\nThis is a test rule with empty frontmatter.",
47+ ),
48+ );
49+
50+ expect(result.frontmatter).toEqual({});
51+ expect(result.markdown).toBe(
52+ "# Test Rule\n\nThis is a test rule with empty frontmatter.",
53+ );
54+ });
55+
56+ it("should handle frontmatter with whitespace", () => {
57+ const content = `---
58+globs: "**/test/**/*.kt"
59+---
60+
61+# Test Rule
62+
63+This is a test rule.`;
64+
65+ const result = parseMarkdownRule(content);
66+ expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
67+ expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
68+ });
69+
70+ it("should handle Windows line endings (CRLF)", () => {
71+ // Using \r\n for CRLF line endings
72+ const content = `---\r
73+globs: "**/test/**/*.kt"\r
74+---\r
75+\r
76+# Test Rule\r
77+\r
78+This is a test rule.`;
79+
80+ const result = parseMarkdownRule(content);
81+ expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
82+ // The result should be normalized to \n
83+ expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
84+ });
85+
86+ it("should handle malformed frontmatter", () => {
87+ const content = `---
88+globs: - "**/test/**/*.kt"
89+invalid: yaml: content
90+---
91+
92+# Test Rule
93+
94+This is a test rule.`;
95+
96+ // Should treat as only markdown when frontmatter is malformed
97+ const result = parseMarkdownRule(content);
98+ expect(result.frontmatter).toEqual({});
99+ expect(result.markdown).toBe(content);
100+ });
101+});
102+
103+describe("convertMarkdownRuleToContinueRule", () => {
104+ it("should convert markdown with frontmatter to a rule", () => {
105+ const content = `---
106+globs: "**/test/**/*.kt"
107+name: Custom Name
108+---
109+
110+# Test Rule
111+
112+This is a test rule.`;
113+
114+ const result = convertMarkdownRuleToContinueRule(
115+ "/path/to/rule.md",
116+ content,
117+ );
118+ expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
119+ expect(result.globs).toBe("**/test/**/*.kt");
120+ expect(result.name).toBe("Custom Name");
121+ expect(result.source).toBe("rules-block");
122+ expect(result.ruleFile).toBe("/path/to/rule.md");
123+ });
124+
125+ it("should use the first heading as name if not in frontmatter", () => {
126+ const content = `---
127+globs: "**/test/**/*.kt"
128+---
129+
130+# Test Rule Title
131+
132+This is a test rule.`;
133+
134+ const result = convertMarkdownRuleToContinueRule(
135+ "/path/to/rule.md",
136+ content,
137+ );
138+ expect(result.name).toBe("Test Rule Title");
139+ });
140+
141+ it("should use filename as name if no heading or frontmatter name", () => {
142+ const content = `---
143+globs: "**/test/**/*.kt"
144+---
145+
146+This is a test rule without a heading.`;
147+
148+ const result = convertMarkdownRuleToContinueRule(
149+ "/path/to/custom-rule.md",
150+ content,
151+ );
152+ expect(result.name).toBe("custom-rule");
153+ });
154+});
added core/config/markdown/parseMarkdownRule.ts +68 −0
@@ -0,0 +1,68 @@
1+import { basename } from "path";
2+import * as YAML from "yaml";
3+import { RuleWithSource } from "../..";
4+
5+/**
6+ * Parses markdown content with YAML frontmatter
7+ */
8+export function parseMarkdownRule(content: string): {
9+ frontmatter: Record<string, any>;
10+ markdown: string;
11+} {
12+ // Normalize line endings to \n
13+ const normalizedContent = content.replace(/\r\n/g, "\n");
14+
15+ // More reliable frontmatter detection
16+ const parts = normalizedContent.split(/^---\s*$/m);
17+
18+ // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter
19+ if (parts.length >= 3) {
20+ const frontmatterStr = parts[1];
21+ // Join the remaining parts back together (in case there are more --- in the markdown)
22+ const markdownContent = parts.slice(2).join("---");
23+
24+ try {
25+ // Parse YAML frontmatter
26+ const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter
27+ return { frontmatter, markdown: markdownContent.trim() };
28+ } catch (e) {
29+ // Error parsing frontmatter, treat as markdown only
30+ console.warn("Error parsing markdown frontmatter:", e);
31+ return { frontmatter: {}, markdown: normalizedContent };
32+ }
33+ }
34+
35+ // No frontmatter found
36+ return { frontmatter: {}, markdown: normalizedContent };
37+}
38+
39+/**
40+ * Converts a markdown file with YAML frontmatter to a RuleWithSource object
41+ */
42+export function convertMarkdownRuleToContinueRule(
43+ path: string,
44+ content: string,
45+): RuleWithSource {
46+ const { frontmatter, markdown } = parseMarkdownRule(content);
47+
48+ // Try to extract title from first heading if no name in frontmatter
49+ let name = frontmatter.name;
50+ if (!name) {
51+ // Look for a heading in the markdown
52+ const headingMatch = markdown.match(/^#\s+(.+)$/m);
53+ if (headingMatch) {
54+ name = headingMatch[1].trim();
55+ } else {
56+ // Fall back to filename
57+ name = basename(path).replace(/\.md$/, "");
58+ }
59+ }
60+
61+ return {
62+ rule: markdown,
63+ globs: frontmatter.globs,
64+ name,
65+ source: "rules-block",
66+ ruleFile: path,
67+ };
68+}
modified core/config/profile/doLoadConfig.ts +7 −0
@@ -32,6 +32,7 @@
3232 import { TTS } from "../../util/tts";
3333 import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
3434 import { loadContinueConfigFromJson } from "../load";
35+import { loadMarkdownRules } from "../markdown/loadMarkdownRules";
3536 import { migrateJsonSharedConfig } from "../migrateSharedConfig";
3637 import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
3738 import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
@@ -128,6 +129,12 @@
128129 newConfig.rules.unshift(...rules);
129130 errors.push(...continueRulesErrors);
130131
132+ // Add rules from markdown files in .continue/rules
133+ const { rules: markdownRules, errors: markdownRulesErrors } =
134+ await loadMarkdownRules(ide);
135+ newConfig.rules.unshift(...markdownRules);
136+ errors.push(...markdownRulesErrors);
137+
131138 // Rectify model selections for each role
132139 newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
133140
modified core/config/yaml/loadYaml.ts +2 −2
@@ -42,7 +42,7 @@
4242
4343 import { getControlPlaneEnvSync } from "../../control-plane/env";
4444 import { getCleanUriPath } from "../../util/uri";
45-import { getAllDotContinueYamlFiles } from "../loadLocalAssistants";
45+import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
4646 import { LocalPlatformClient } from "./LocalPlatformClient";
4747 import { llmsFromModelConfig } from "./models";
4848
@@ -96,7 +96,7 @@
9696 // Add local .continue blocks
9797 const allLocalBlocks: PackageIdentifier[] = [];
9898 for (const blockType of BLOCK_TYPES) {
99- const localBlocks = await getAllDotContinueYamlFiles(
99+ const localBlocks = await getAllDotContinueDefinitionFiles(
100100 ide,
101101 { includeGlobal: true, includeWorkspace: true },
102102 blockType,
modified core/tools/implementations/createRuleBlock.ts +35 −10
@@ -7,6 +7,7 @@
77 name: string;
88 rule: string;
99 globs?: string;
10+ format?: "yaml" | "markdown"; // Add format option with yaml as default
1011 }
1112
1213 export const createRuleBlockImpl: ToolImpl = async (
@@ -19,30 +20,54 @@
1920 .replace(/[^a-z0-9\s-]/g, "")
2021 .replace(/\s+/g, "-");
2122
23+ // Default to YAML format
24+ const format = args.format ?? "yaml";
25+ const fileExtension = format === "markdown" ? "md" : "yaml";
26+
2227 const ruleObject = {
2328 name: args.name,
2429 rule: args.rule,
2530 ...(args.globs ? { globs: args.globs.trim() } : {}),
2631 };
2732
28- const ruleBlock: ConfigYaml = {
29- name: args.name,
30- version: "0.0.1",
31- schema: "v1",
32- rules: [ruleObject],
33- };
33+ let fileContent: string;
34+
35+ if (format === "markdown") {
36+ // Generate markdown format with frontmatter
37+ const frontmatter = {
38+ ...(args.globs ? { globs: args.globs.trim() } : {}),
39+ };
40+
41+ const frontmatterYaml = YAML.stringify(frontmatter).trim();
42+ fileContent = `---
43+${frontmatterYaml}
44+---
45+
46+# ${args.name}
47+
48+${args.rule}
49+`;
50+ } else {
51+ // Generate YAML format
52+ const ruleBlock: ConfigYaml = {
53+ name: args.name,
54+ version: "0.0.1",
55+ schema: "v1",
56+ rules: [ruleObject],
57+ };
3458
35- const ruleYaml = YAML.stringify(ruleBlock);
59+ fileContent = YAML.stringify(ruleBlock);
60+ }
3661
3762 const [localContinueDir] = await extras.ide.getWorkspaceDirs();
3863 const rulesDirUri = joinPathsToUri(
3964 localContinueDir,
4065 ".continue",
4166 "rules",
42- `${safeRuleName}.yaml`,
67+ `${safeRuleName}.${fileExtension}`,
4368 );
4469
45- await extras.ide.writeFile(rulesDirUri, ruleYaml);
70+ await extras.ide.writeFile(rulesDirUri, fileContent);
4671 await extras.ide.openFile(rulesDirUri);
4772
4873 return [
@@ -53,7 +78,7 @@
5378 type: "file",
5479 value: rulesDirUri,
5580 },
56- content: "Rule created successfully",
81+ content: `Rule created successfully in ${format} format`,
5782 },
5883 ];
5984 };
modified extensions/vscode/package.json +1 −1
@@ -2,7 +2,7 @@
22 "name": "continue",
33 "icon": "media/icon.png",
44 "author": "Continue Dev, Inc",
5- "version": "1.1.37",
5+ "version": "1.1.38",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"