From c15dfc242c9972b3885d237c88e44333a475930a Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 16 Jul 2025 11:12:04 -0700 Subject: [PATCH] Add --rule flag support for loading custom rules from files, hub, or direct strings --- src/args.test.ts | 58 ++++++++++++++++++++++++++++++-- src/args.ts | 73 +++++++++++++++++++++++++++++++++++++++-- src/commands/chat.ts | 6 ++-- src/index.ts | 8 ++++- src/systemMessage.ts | 29 +++++++++++++--- src/ui/TUIChat.tsx | 3 ++ src/ui/hooks/useChat.ts | 6 ++-- src/ui/index.ts | 6 ++-- test-rule.md | 9 +++++ 9 files changed, 182 insertions(+), 16 deletions(-) create mode 100644 test-rule.md diff --git a/src/args.test.ts b/src/args.test.ts index 0d1779095..4ebb8822b 100644 --- a/src/args.test.ts +++ b/src/args.test.ts @@ -50,6 +50,18 @@ describe('parseArgs', () => { expect(result.configPath).toBe('/path/to/config.yaml'); }); + it('should parse single rule from --rule flag', () => { + process.argv = ['node', 'script.js', '--rule', 'my-rule']; + const result = parseArgs(); + expect(result.rules).toEqual(['my-rule']); + }); + + it('should parse multiple rules from multiple --rule flags', () => { + process.argv = ['node', 'script.js', '--rule', 'rule1', '--rule', 'rule2']; + const result = parseArgs(); + expect(result.rules).toEqual(['rule1', 'rule2']); + }); + it('should parse prompt from last non-flag argument', () => { process.argv = ['node', 'script.js', 'Hello world']; const result = parseArgs(); @@ -75,6 +87,15 @@ describe('parseArgs', () => { }); }); + it('should handle rule flag with other flags', () => { + process.argv = ['node', 'script.js', '--rule', 'my-rule', '--headless']; + const result = parseArgs(); + expect(result).toEqual({ + isHeadless: true, + rules: ['my-rule'], + }); + }); + it('should handle prompt with flags', () => { process.argv = ['node', 'script.js', '--headless', 'What is the weather?']; const result = parseArgs(); @@ -94,11 +115,22 @@ describe('parseArgs', () => { }); }); - it('should ignore config flag value when extracting prompt', () => { - process.argv = ['node', 'script.js', '--config', 'config.yaml', 'actual-prompt']; + it('should handle rule flag with prompt', () => { + process.argv = ['node', 'script.js', '--rule', 'my-rule', 'Test prompt']; + const result = parseArgs(); + expect(result).toEqual({ + isHeadless: false, + rules: ['my-rule'], + prompt: 'Test prompt', + }); + }); + + it('should ignore config and rule flag values when extracting prompt', () => { + process.argv = ['node', 'script.js', '--config', 'config.yaml', '--rule', 'my-rule', 'actual-prompt']; const result = parseArgs(); expect(result.prompt).toBe('actual-prompt'); expect(result.configPath).toBe('config.yaml'); + expect(result.rules).toEqual(['my-rule']); }); it('should handle multiple non-flag arguments and use the last one as prompt', () => { @@ -108,11 +140,12 @@ describe('parseArgs', () => { }); it('should handle complex argument combinations', () => { - process.argv = ['node', 'script.js', '--headless', '--config', 'my-config.yaml', '--readonly', '--resume', 'Complex prompt with spaces']; + process.argv = ['node', 'script.js', '--headless', '--config', 'my-config.yaml', '--rule', 'rule1', '--rule', 'rule2', '--readonly', '--resume', 'Complex prompt with spaces']; const result = parseArgs(); expect(result).toEqual({ isHeadless: true, configPath: 'my-config.yaml', + rules: ['rule1', 'rule2'], readonly: true, resume: true, prompt: 'Complex prompt with spaces', @@ -125,6 +158,12 @@ describe('parseArgs', () => { expect(result.configPath).toBeUndefined(); }); + it('should handle rule flag without value', () => { + process.argv = ['node', 'script.js', '--rule']; + const result = parseArgs(); + expect(result.rules).toEqual([]); + }); + it('should handle config flag at the end without value', () => { process.argv = ['node', 'script.js', '--headless', '--config']; const result = parseArgs(); @@ -132,6 +171,13 @@ describe('parseArgs', () => { expect(result.configPath).toBeUndefined(); }); + it('should handle rule flag at the end without value', () => { + process.argv = ['node', 'script.js', '--headless', '--rule']; + const result = parseArgs(); + expect(result.isHeadless).toBe(true); + expect(result.rules).toEqual([]); + }); + it('should handle empty arguments array', () => { process.argv = ['node', 'script.js']; const result = parseArgs(); @@ -146,4 +192,10 @@ describe('parseArgs', () => { expect(result.noTools).toBe(true); expect(result.readonly).toBe(true); }); + + it('should handle multiple rules with complex combinations', () => { + process.argv = ['node', 'script.js', '--rule', 'file.txt', '--rule', 'owner/package', '--rule', 'direct string rule']; + const result = parseArgs(); + expect(result.rules).toEqual(['file.txt', 'owner/package', 'direct string rule']); + }); }); \ No newline at end of file diff --git a/src/args.ts b/src/args.ts index ec20826f1..75a7f8c58 100644 --- a/src/args.ts +++ b/src/args.ts @@ -1,3 +1,6 @@ +import * as fs from "fs"; +import * as path from "path"; + export interface CommandLineArgs { isHeadless: boolean; configPath?: string; @@ -5,6 +8,54 @@ export interface CommandLineArgs { resume?: boolean; // Resume from last session readonly?: boolean; // Only allow readonly tools noTools?: boolean; // Disable all tools + rules?: string[]; // Array of rule specifications +} + +/** + * Load rule content from a file path + * @param filePath - Path to the rule file + * @returns The content of the rule file + */ +function loadRuleFromFile(filePath: string): string { + try { + const absolutePath = path.resolve(filePath); + if (!fs.existsSync(absolutePath)) { + throw new Error(`Rule file not found: ${filePath}`); + } + return fs.readFileSync(absolutePath, "utf-8"); + } catch (error: any) { + throw new Error(`Failed to read rule file "${filePath}": ${error.message}`); + } +} + +/** + * Load rule content from hub.continue.dev (not yet implemented) + * @param slug - The slug in format "owner/package" + * @returns The rule content from the hub + */ +function loadRuleFromHub(slug: string): string { + // TODO: Implement hub integration + throw new Error(`Hub rules not yet supported: ${slug}`); +} + +/** + * Process a rule specification and return its content + * @param ruleSpec - Can be a file path, hub slug, or direct string content + * @returns The processed rule content + */ +export function processRule(ruleSpec: string): string { + // If it looks like a hub slug (contains / but doesn't start with . or /) + if (ruleSpec.includes("/") && !ruleSpec.startsWith(".") && !ruleSpec.startsWith("/")) { + return loadRuleFromHub(ruleSpec); + } + + // If it looks like a file path (contains . or / or ends with common file extensions) + if (ruleSpec.includes(".") || ruleSpec.includes("/") || ruleSpec.includes("\\")) { + return loadRuleFromFile(ruleSpec); + } + + // Otherwise, treat it as direct string content + return ruleSpec; } /** @@ -42,14 +93,32 @@ export function parseArgs(): CommandLineArgs { result.configPath = args[configIndex + 1]; } + // Get rules from --rule flags (can be specified multiple times) + const ruleIndices: number[] = []; + for (let i = 0; i < args.length; i++) { + if (args[i] === "--rule") { + ruleIndices.push(i); + } + } + + if (ruleIndices.length > 0) { + result.rules = []; + for (const ruleIndex of ruleIndices) { + if (ruleIndex + 1 < args.length) { + result.rules.push(args[ruleIndex + 1]); + } + } + } + // Find the last argument that's not a flag or a flag value + const flagsWithValues = ["--config", "--rule"]; const nonFlagArgs = args.filter((arg, index) => { // Skip flags (starting with --) if (arg.startsWith("--")) return false; // Skip flag values const prevArg = index > 0 ? args[index - 1] : ""; - if (prevArg === "--config") return false; + if (flagsWithValues.includes(prevArg)) return false; return true; }); @@ -60,4 +129,4 @@ export function parseArgs(): CommandLineArgs { } return result; -} +} \ No newline at end of file diff --git a/src/commands/chat.ts b/src/commands/chat.ts index a328bc30b..ee3c09be9 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -15,6 +15,7 @@ export interface ChatOptions { headless?: boolean; config?: string; resume?: boolean; + rule?: string[]; // Array of rule specifications } async function initializeChat(options: ChatOptions) { @@ -56,7 +57,8 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { mcpService, prompt, options.resume, - options.config + options.config, + options.rule ); return; } @@ -83,7 +85,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { // If no session loaded or not resuming, initialize with system message if (chatHistory.length === 0) { const rulesSystemMessage = ""; // TODO //assistant.systemMessage; - const systemMessage = constructSystemMessage(rulesSystemMessage); + const systemMessage = constructSystemMessage(rulesSystemMessage, options.rule); if (systemMessage) { chatHistory.push({ role: "system", content: systemMessage }); } diff --git a/src/index.ts b/src/index.ts index 4fe125e30..86486d402 100644 --- a/src/index.ts +++ b/src/index.ts @@ -32,6 +32,12 @@ program .option("--resume", "Resume from last session") .option("--readonly", "Only allow readonly tools") .option("--no-tools", "Disable all tools") + .option("--rule ", "Add a rule (can be a file path, hub slug, or string content). Can be specified multiple times.", + (value: string, previous: string[] | undefined) => { + const array = Array.isArray(previous) ? previous : []; + array.push(value); + return array; + }, [] as string[]) .action(async (prompt, options) => { await chat(prompt, options); }); @@ -52,4 +58,4 @@ program await logout(); }); -program.parse(); +program.parse(); \ No newline at end of file diff --git a/src/systemMessage.ts b/src/systemMessage.ts index bae4fa898..fe456f533 100644 --- a/src/systemMessage.ts +++ b/src/systemMessage.ts @@ -3,6 +3,7 @@ import * as fs from "fs"; import pkg from "ignore-walk"; import { Minimatch } from "minimatch"; import * as path from "path"; +import { processRule } from "./args.js"; const { WalkerSync } = pkg; /** @@ -95,9 +96,10 @@ ${getGitStatus()} /** * Load and construct a comprehensive system message with base message and rules section * @param rulesSystemMessage - The rules system message from the assistant + * @param additionalRules - Additional rules from --rule flags * @returns The comprehensive system message with base message and rules section */ -export function constructSystemMessage(rulesSystemMessage: string): string { +export function constructSystemMessage(rulesSystemMessage: string, additionalRules?: string[]): string { const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"]; let agentContent = ""; @@ -116,11 +118,24 @@ export function constructSystemMessage(rulesSystemMessage: string): string { console.warn("Warning: Could not read agent configuration file:", error); } + // Process additional rules from --rule flags + let processedRules: string[] = []; + if (additionalRules && additionalRules.length > 0) { + for (const ruleSpec of additionalRules) { + try { + const processedRule = processRule(ruleSpec); + processedRules.push(processedRule); + } catch (error: any) { + console.warn(`Warning: Failed to process rule "${ruleSpec}": ${error.message}`); + } + } + } + // Construct the comprehensive system message let systemMessage = baseSystemMessage; - // Add rules section if we have either rules or agent content - if (rulesSystemMessage || agentContent) { + // Add rules section if we have any rules or agent content + if (rulesSystemMessage || agentContent || processedRules.length > 0) { systemMessage += '\n\n'; if (rulesSystemMessage) { @@ -132,8 +147,14 @@ export function constructSystemMessage(rulesSystemMessage: string): string { systemMessage += `${separator}${agentContent}`; } + // Add processed rules from --rule flags + if (processedRules.length > 0) { + const separator = (rulesSystemMessage || agentContent) ? "\n\n" : "\n"; + systemMessage += `${separator}${processedRules.join("\n\n")}`; + } + systemMessage += "\n"; } return systemMessage; -} +} \ No newline at end of file diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index ba0cff87a..ea84a3734 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -23,6 +23,7 @@ interface TUIChatProps { configPath?: string; initialPrompt?: string; resume?: boolean; + additionalRules?: string[]; } const TUIChat: React.FC = ({ @@ -33,6 +34,7 @@ const TUIChat: React.FC = ({ configPath, initialPrompt, resume, + additionalRules, }) => { // Track current assistant configuration state const [assistant, setAssistant] = useState(initialAssistant); @@ -109,6 +111,7 @@ const TUIChat: React.FC = ({ llmApi, initialPrompt, resume, + additionalRules, onShowOrgSelector: () => showOrganizationSelector(), onShowConfigSelector: () => showConfigSelectorUI(), onLoginPrompt: handleLoginPrompt, diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 498066bcd..29eed0787 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -22,6 +22,7 @@ interface UseChatProps { llmApi: BaseLlmApi; initialPrompt?: string; resume?: boolean; + additionalRules?: string[]; onShowOrgSelector: () => void; onShowConfigSelector: () => void; onLoginPrompt?: (promptText: string) => Promise; @@ -34,6 +35,7 @@ export function useChat({ llmApi, initialPrompt, resume, + additionalRules, onShowOrgSelector, onShowConfigSelector, onLoginPrompt, @@ -54,7 +56,7 @@ export function useChat({ if (history.length === 0) { const rulesSystemMessage = ""; - const systemMessage = constructSystemMessage(rulesSystemMessage); + const systemMessage = constructSystemMessage(rulesSystemMessage, additionalRules); if (systemMessage) { history.push({ role: "system", content: systemMessage }); } @@ -348,7 +350,7 @@ export function useChat({ const resetChatHistory = () => { const rulesSystemMessage = ""; - const systemMessage = constructSystemMessage(rulesSystemMessage); + const systemMessage = constructSystemMessage(rulesSystemMessage, additionalRules); const newHistory = systemMessage ? [{ role: "system" as const, content: systemMessage }] : []; diff --git a/src/ui/index.ts b/src/ui/index.ts index 12711075d..ea540841f 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -15,7 +15,8 @@ export async function startTUIChat( mcpService: MCPService, initialPrompt?: string, resume?: boolean, - configPath?: string + configPath?: string, + additionalRules?: string[] ) { // Show intro message before starting TUI introMessage(config, model, mcpService); @@ -30,6 +31,7 @@ export async function startTUIChat( configPath, initialPrompt, resume, + additionalRules, }) ); @@ -40,4 +42,4 @@ export async function startTUIChat( }); return { unmount }; -} +} \ No newline at end of file diff --git a/test-rule.md b/test-rule.md new file mode 100644 index 000000000..f23ebcdb2 --- /dev/null +++ b/test-rule.md @@ -0,0 +1,9 @@ +# Test Rule + +This is a test rule file for validating the --rule flag functionality. + +## Instructions + +- Always respond with enthusiasm +- Use simple, clear language +- Provide code examples when relevant \ No newline at end of file