Merge pull request #5760 from continuedev/tomasz/markdown-rules
feat: markdown rules
This commit is contained in:
commit
50765d8970
9 changed files with 321 additions and 20 deletions
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
@ -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 }[]> {
|
||||
|
|
@ -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
|
||||
|
|
@ -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(
|
||||
|
|
|
|||
47
core/config/markdown/loadMarkdownRules.ts
Normal file
47
core/config/markdown/loadMarkdownRules.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
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<{
|
||||
rules: RuleWithSource[];
|
||||
errors: ConfigValidationError[];
|
||||
}> {
|
||||
const errors: ConfigValidationError[] = [];
|
||||
const rules: RuleWithSource[] = [];
|
||||
|
||||
try {
|
||||
// Get all .md files from .continue/rules
|
||||
const markdownFiles = await getAllDotContinueDefinitionFiles(
|
||||
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 };
|
||||
}
|
||||
154
core/config/markdown/parseMarkdownRule.test.ts
Normal file
154
core/config/markdown/parseMarkdownRule.test.ts
Normal file
|
|
@ -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");
|
||||
});
|
||||
});
|
||||
68
core/config/markdown/parseMarkdownRule.ts
Normal file
68
core/config/markdown/parseMarkdownRule.ts
Normal file
|
|
@ -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<string, any>;
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
|
@ -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);
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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`,
|
||||
},
|
||||
];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue