diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index ccc70c092..bdfe0aa0a 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -7,6 +7,7 @@ import { } from "../.."; import { renderChatMessage } from "../../util/messageContent"; import { getCleanUriPath } from "../../util/uri"; +import { extractContentFromCodeBlock } from "../utils/extractContentFromCodeBlocks"; import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; import { RulePolicies } from "./types"; @@ -305,11 +306,25 @@ export const getApplicableRules = ( // Extract contents from context items with file URIs contextItems.forEach((item) => { - console.log("ITEM", item); if (item.uri?.type === "file" && item.uri?.value) { fileContents[item.uri.value] = item.content; } }); + + // Extract contents from code blocks in the message for paths that don't have content yet + if (userMessage) { + const messageContent = renderChatMessage(userMessage); + filePathsFromMessage.forEach((path) => { + // Only extract content if we don't already have it from context items + if (!fileContents[path]) { + const blockContent = extractContentFromCodeBlock(messageContent, path); + if (blockContent) { + fileContents[path] = blockContent; + } + } + }); + } + console.log("FILE CONTENTS", fileContents); // Apply shouldApplyRule to all rules - this will handle global rules, rule policies, diff --git a/core/llm/utils/extractContentFromCodeBlocks.ts b/core/llm/utils/extractContentFromCodeBlocks.ts new file mode 100644 index 000000000..00abc49cf --- /dev/null +++ b/core/llm/utils/extractContentFromCodeBlocks.ts @@ -0,0 +1,29 @@ +/** + * Extracts content from code blocks with given path + * @param content The full message content + * @param path The file path to look for + * @returns The content of the code block if found, undefined otherwise + */ +export function extractContentFromCodeBlock( + content: string, + path: string +): string | undefined { + // Escape special characters in the path for regex + const escapedPath = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + + // Match the code block with this path + // This regex looks for: + // 1. Code block start with the path (```[language] path) + // 2. The content until the closing ``` + const regex = new RegExp( + `\`\`\`[^\\n]*${escapedPath}[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``, + "m" + ); + + const match = content.match(regex); + if (match && match[1]) { + return match[1]; + } + + return undefined; +} \ No newline at end of file