From a21d350ea14a98cf16904ae678de64a83775da7c Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 20 May 2025 12:36:01 -0700 Subject: [PATCH 1/3] feat: markdown rules fix: parsing --- core/config/loadLocalAssistants.ts | 4 +- core/config/markdown/loadMarkdownRules.ts | 49 ++++++ .../config/markdown/parseMarkdownRule.test.ts | 154 ++++++++++++++++++ core/config/markdown/parseMarkdownRule.ts | 68 ++++++++ core/config/profile/doLoadConfig.ts | 7 + core/tools/implementations/createRuleBlock.ts | 45 +++-- 6 files changed, 315 insertions(+), 12 deletions(-) create mode 100644 core/config/markdown/loadMarkdownRules.ts create mode 100644 core/config/markdown/parseMarkdownRule.test.ts create mode 100644 core/config/markdown/parseMarkdownRule.ts diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts index 18e24f58d..7f012e6db 100644 --- a/core/config/loadLocalAssistants.ts +++ b/core/config/loadLocalAssistants.ts @@ -13,7 +13,7 @@ export const ASSISTANTS = "assistants"; export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`; export function isLocalAssistantFile(uri: string): boolean { - if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) { + if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) { return false; } @@ -41,7 +41,7 @@ export async function listYamlFilesInDir( source: "get assistant files", }); const assistantFilePaths = uris.filter( - (p) => p.endsWith(".yaml") || p.endsWith(".yml"), + (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"), ); const results = assistantFilePaths.map(async (uri) => { const content = await ide.readFile(uri); // make a try catch diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts new file mode 100644 index 000000000..24cd0caac --- /dev/null +++ b/core/config/markdown/loadMarkdownRules.ts @@ -0,0 +1,49 @@ +import { IDE, RuleWithSource } from "../.."; +import { getAllDotContinueYamlFiles } from "../loadLocalAssistants"; +import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule"; +import { ConfigValidationError } from "@continuedev/config-yaml"; + +/** + * Loads rules from markdown files in the .continue/rules directory + */ +export async function loadMarkdownRules( + ide: IDE +): Promise<{ + rules: RuleWithSource[]; + errors: ConfigValidationError[]; +}> { + const errors: ConfigValidationError[] = []; + const rules: RuleWithSource[] = []; + + try { + // Get all .md files from .continue/rules + const markdownFiles = await getAllDotContinueYamlFiles( + ide, + { includeGlobal: true, includeWorkspace: true }, + "rules" + ); + + // Filter to just .md files + const mdFiles = markdownFiles.filter(file => file.path.endsWith('.md')); + + // Process each markdown file + for (const file of mdFiles) { + try { + const rule = convertMarkdownRuleToContinueRule(file.path, file.content); + rules.push(rule); + } catch (e) { + errors.push({ + fatal: false, + message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}` + }); + } + } + } catch (e) { + errors.push({ + fatal: false, + message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}` + }); + } + + return { rules, errors }; +} \ No newline at end of file diff --git a/core/config/markdown/parseMarkdownRule.test.ts b/core/config/markdown/parseMarkdownRule.test.ts new file mode 100644 index 000000000..a34f8814d --- /dev/null +++ b/core/config/markdown/parseMarkdownRule.test.ts @@ -0,0 +1,154 @@ +import { + convertMarkdownRuleToContinueRule, + parseMarkdownRule, +} from "./parseMarkdownRule"; + +describe("parseMarkdownRule", () => { + it("should correctly parse markdown with YAML frontmatter", () => { + const content = `--- +globs: "**/test/**/*.kt" +--- + +# Test Rule + +This is a test rule.`; + + const result = parseMarkdownRule(content); + expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); + expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); + }); + + it("should handle missing frontmatter", () => { + const content = `# Test Rule + +This is a test rule without frontmatter.`; + + const result = parseMarkdownRule(content); + expect(result.frontmatter).toEqual({}); + expect(result.markdown).toBe(content); + }); + + it("should handle empty frontmatter", () => { + const content = `--- +--- + +# Test Rule + +This is a test rule with empty frontmatter.`; + + const result = parseMarkdownRule(content); + + // Log exact strings for debugging + console.log("Actual:", JSON.stringify(result.markdown)); + console.log( + "Expected:", + JSON.stringify( + "# Test Rule\n\nThis is a test rule with empty frontmatter.", + ), + ); + + expect(result.frontmatter).toEqual({}); + expect(result.markdown).toBe( + "# Test Rule\n\nThis is a test rule with empty frontmatter.", + ); + }); + + it("should handle frontmatter with whitespace", () => { + const content = `--- +globs: "**/test/**/*.kt" +--- + +# Test Rule + +This is a test rule.`; + + const result = parseMarkdownRule(content); + expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); + expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); + }); + + it("should handle Windows line endings (CRLF)", () => { + // Using \r\n for CRLF line endings + const content = `---\r +globs: "**/test/**/*.kt"\r +---\r +\r +# Test Rule\r +\r +This is a test rule.`; + + const result = parseMarkdownRule(content); + expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); + // The result should be normalized to \n + expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); + }); + + it("should handle malformed frontmatter", () => { + const content = `--- +globs: - "**/test/**/*.kt" +invalid: yaml: content +--- + +# Test Rule + +This is a test rule.`; + + // Should treat as only markdown when frontmatter is malformed + const result = parseMarkdownRule(content); + expect(result.frontmatter).toEqual({}); + expect(result.markdown).toBe(content); + }); +}); + +describe("convertMarkdownRuleToContinueRule", () => { + it("should convert markdown with frontmatter to a rule", () => { + const content = `--- +globs: "**/test/**/*.kt" +name: Custom Name +--- + +# Test Rule + +This is a test rule.`; + + const result = convertMarkdownRuleToContinueRule( + "/path/to/rule.md", + content, + ); + expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); + expect(result.globs).toBe("**/test/**/*.kt"); + expect(result.name).toBe("Custom Name"); + expect(result.source).toBe("rules-block"); + expect(result.ruleFile).toBe("/path/to/rule.md"); + }); + + it("should use the first heading as name if not in frontmatter", () => { + const content = `--- +globs: "**/test/**/*.kt" +--- + +# Test Rule Title + +This is a test rule.`; + + const result = convertMarkdownRuleToContinueRule( + "/path/to/rule.md", + content, + ); + expect(result.name).toBe("Test Rule Title"); + }); + + it("should use filename as name if no heading or frontmatter name", () => { + const content = `--- +globs: "**/test/**/*.kt" +--- + +This is a test rule without a heading.`; + + const result = convertMarkdownRuleToContinueRule( + "/path/to/custom-rule.md", + content, + ); + expect(result.name).toBe("custom-rule"); + }); +}); diff --git a/core/config/markdown/parseMarkdownRule.ts b/core/config/markdown/parseMarkdownRule.ts new file mode 100644 index 000000000..a876bced2 --- /dev/null +++ b/core/config/markdown/parseMarkdownRule.ts @@ -0,0 +1,68 @@ +import { basename } from "path"; +import * as YAML from "yaml"; +import { RuleWithSource } from "../.."; + +/** + * Parses markdown content with YAML frontmatter + */ +export function parseMarkdownRule(content: string): { + frontmatter: Record; + markdown: string; +} { + // Normalize line endings to \n + const normalizedContent = content.replace(/\r\n/g, "\n"); + + // More reliable frontmatter detection + const parts = normalizedContent.split(/^---\s*$/m); + + // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter + if (parts.length >= 3) { + const frontmatterStr = parts[1]; + // Join the remaining parts back together (in case there are more --- in the markdown) + const markdownContent = parts.slice(2).join("---"); + + try { + // Parse YAML frontmatter + const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter + return { frontmatter, markdown: markdownContent.trim() }; + } catch (e) { + // Error parsing frontmatter, treat as markdown only + console.warn("Error parsing markdown frontmatter:", e); + return { frontmatter: {}, markdown: normalizedContent }; + } + } + + // No frontmatter found + return { frontmatter: {}, markdown: normalizedContent }; +} + +/** + * Converts a markdown file with YAML frontmatter to a RuleWithSource object + */ +export function convertMarkdownRuleToContinueRule( + path: string, + content: string, +): RuleWithSource { + const { frontmatter, markdown } = parseMarkdownRule(content); + + // Try to extract title from first heading if no name in frontmatter + let name = frontmatter.name; + if (!name) { + // Look for a heading in the markdown + const headingMatch = markdown.match(/^#\s+(.+)$/m); + if (headingMatch) { + name = headingMatch[1].trim(); + } else { + // Fall back to filename + name = basename(path).replace(/\.md$/, ""); + } + } + + return { + rule: markdown, + globs: frontmatter.globs, + name, + source: "rules-block", + ruleFile: path, + }; +} diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 1308ca2a0..cc1b98e49 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -32,6 +32,7 @@ import { Telemetry } from "../../util/posthog"; import { TTS } from "../../util/tts"; import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles"; import { loadContinueConfigFromJson } from "../load"; +import { loadMarkdownRules } from "../markdown/loadMarkdownRules"; import { migrateJsonSharedConfig } from "../migrateSharedConfig"; import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; @@ -128,6 +129,12 @@ export default async function doLoadConfig(options: { newConfig.rules.unshift(...rules); errors.push(...continueRulesErrors); + // Add rules from markdown files in .continue/rules + const { rules: markdownRules, errors: markdownRulesErrors } = + await loadMarkdownRules(ide); + newConfig.rules.unshift(...markdownRules); + errors.push(...markdownRulesErrors); + // Rectify model selections for each role newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId); diff --git a/core/tools/implementations/createRuleBlock.ts b/core/tools/implementations/createRuleBlock.ts index 87702e866..ea2514709 100644 --- a/core/tools/implementations/createRuleBlock.ts +++ b/core/tools/implementations/createRuleBlock.ts @@ -7,6 +7,7 @@ export interface CreateRuleBlockArgs { name: string; rule: string; globs?: string; + format?: "yaml" | "markdown"; // Add format option with yaml as default } export const createRuleBlockImpl: ToolImpl = async ( @@ -19,30 +20,54 @@ export const createRuleBlockImpl: ToolImpl = async ( .replace(/[^a-z0-9\s-]/g, "") .replace(/\s+/g, "-"); + // Default to YAML format + const format = args.format ?? "yaml"; + const fileExtension = format === "markdown" ? "md" : "yaml"; + const ruleObject = { name: args.name, rule: args.rule, ...(args.globs ? { globs: args.globs.trim() } : {}), }; - const ruleBlock: ConfigYaml = { - name: args.name, - version: "0.0.1", - schema: "v1", - rules: [ruleObject], - }; + let fileContent: string; - const ruleYaml = YAML.stringify(ruleBlock); + if (format === "markdown") { + // Generate markdown format with frontmatter + const frontmatter = { + ...(args.globs ? { globs: args.globs.trim() } : {}), + }; + + const frontmatterYaml = YAML.stringify(frontmatter).trim(); + fileContent = `--- +${frontmatterYaml} +--- + +# ${args.name} + +${args.rule} +`; + } else { + // Generate YAML format + const ruleBlock: ConfigYaml = { + name: args.name, + version: "0.0.1", + schema: "v1", + rules: [ruleObject], + }; + + fileContent = YAML.stringify(ruleBlock); + } const [localContinueDir] = await extras.ide.getWorkspaceDirs(); const rulesDirUri = joinPathsToUri( localContinueDir, ".continue", "rules", - `${safeRuleName}.yaml`, + `${safeRuleName}.${fileExtension}`, ); - await extras.ide.writeFile(rulesDirUri, ruleYaml); + await extras.ide.writeFile(rulesDirUri, fileContent); await extras.ide.openFile(rulesDirUri); return [ @@ -53,7 +78,7 @@ export const createRuleBlockImpl: ToolImpl = async ( type: "file", value: rulesDirUri, }, - content: "Rule created successfully", + content: `Rule created successfully in ${format} format`, }, ]; }; From ba3984290ddb875608845904d31c5a5d57b1bf03 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 20 May 2025 13:24:33 -0700 Subject: [PATCH 2/3] fix: naming --- core/config/ConfigHandler.ts | 4 ++-- core/config/loadLocalAssistants.ts | 6 +++--- core/config/markdown/loadMarkdownRules.ts | 22 ++++++++++------------ core/config/yaml/loadYaml.ts | 4 ++-- 4 files changed, 17 insertions(+), 19 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index deae7da38..0d4d81b30 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -19,7 +19,7 @@ import { getControlPlaneEnv } from "../control-plane/env.js"; import { logger } from "../util/logger.js"; import { ASSISTANTS, - getAllDotContinueYamlFiles, + getAllDotContinueDefinitionFiles, LoadAssistantFilesOptions, } from "./loadLocalAssistants.js"; import LocalProfileLoader from "./profile/LocalProfileLoader.js"; @@ -284,7 +284,7 @@ export class ConfigHandler { } if (options.includeWorkspace) { - const assistantFiles = await getAllDotContinueYamlFiles( + const assistantFiles = await getAllDotContinueDefinitionFiles( this.ide, options, ASSISTANTS, diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts index 7f012e6db..90c5922a2 100644 --- a/core/config/loadLocalAssistants.ts +++ b/core/config/loadLocalAssistants.ts @@ -21,7 +21,7 @@ export function isLocalAssistantFile(uri: string): boolean { return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`); } -export async function listYamlFilesInDir( +async function getDefinitionFilesInDir( ide: IDE, dir: string, ): Promise<{ path: string; content: string }[]> { @@ -86,7 +86,7 @@ export function getDotContinueSubDirs( * This method searches in both ~/.continue and workspace .continue * for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts */ -export async function getAllDotContinueYamlFiles( +export async function getAllDotContinueDefinitionFiles( ide: IDE, options: LoadAssistantFilesOptions, subDirName: string, @@ -103,7 +103,7 @@ export async function getAllDotContinueYamlFiles( // Get all assistant files from the directories const assistantFiles = ( - await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir))) + await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir))) ).flat(); return await Promise.all( diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts index 24cd0caac..b0bbb8005 100644 --- a/core/config/markdown/loadMarkdownRules.ts +++ b/core/config/markdown/loadMarkdownRules.ts @@ -1,14 +1,12 @@ -import { IDE, RuleWithSource } from "../.."; -import { getAllDotContinueYamlFiles } from "../loadLocalAssistants"; -import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule"; import { ConfigValidationError } from "@continuedev/config-yaml"; +import { IDE, RuleWithSource } from "../.."; +import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; +import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule"; /** * Loads rules from markdown files in the .continue/rules directory */ -export async function loadMarkdownRules( - ide: IDE -): Promise<{ +export async function loadMarkdownRules(ide: IDE): Promise<{ rules: RuleWithSource[]; errors: ConfigValidationError[]; }> { @@ -17,14 +15,14 @@ export async function loadMarkdownRules( try { // Get all .md files from .continue/rules - const markdownFiles = await getAllDotContinueYamlFiles( + const markdownFiles = await getAllDotContinueDefinitionFiles( ide, { includeGlobal: true, includeWorkspace: true }, - "rules" + "rules", ); // Filter to just .md files - const mdFiles = markdownFiles.filter(file => file.path.endsWith('.md')); + const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md")); // Process each markdown file for (const file of mdFiles) { @@ -34,16 +32,16 @@ export async function loadMarkdownRules( } catch (e) { errors.push({ fatal: false, - message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}` + message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`, }); } } } catch (e) { errors.push({ fatal: false, - message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}` + message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}`, }); } return { rules, errors }; -} \ No newline at end of file +} diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 8c926faab..7c18aec00 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -42,7 +42,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { getControlPlaneEnvSync } from "../../control-plane/env"; import { getCleanUriPath } from "../../util/uri"; -import { getAllDotContinueYamlFiles } from "../loadLocalAssistants"; +import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; import { LocalPlatformClient } from "./LocalPlatformClient"; import { llmsFromModelConfig } from "./models"; @@ -96,7 +96,7 @@ async function loadConfigYaml(options: { // Add local .continue blocks const allLocalBlocks: PackageIdentifier[] = []; for (const blockType of BLOCK_TYPES) { - const localBlocks = await getAllDotContinueYamlFiles( + const localBlocks = await getAllDotContinueDefinitionFiles( ide, { includeGlobal: true, includeWorkspace: true }, blockType, From de26681c9c4a5782f0848153e7eca776929bc157 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 20 May 2025 16:15:57 -0700 Subject: [PATCH 3/3] bump --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 3772dd79d..2657b6258 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.37", + "version": "1.1.38", "repository": { "type": "git", "url": "https://github.com/continuedev/continue"