Add --rule flag support for loading custom rules from files, hub, or direct strings

This commit is contained in:
Nate 2025-07-16 11:12:04 -07:00
parent a90695ed81
commit c15dfc242c
9 changed files with 182 additions and 16 deletions

View file

@ -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']);
});
});

View file

@ -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;
}
}

View file

@ -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 });
}

View file

@ -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 <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();

View file

@ -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<context name="userRules">';
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</context>";
}
return systemMessage;
}
}

View file

@ -23,6 +23,7 @@ interface TUIChatProps {
configPath?: string;
initialPrompt?: string;
resume?: boolean;
additionalRules?: string[];
}
const TUIChat: React.FC<TUIChatProps> = ({
@ -33,6 +34,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
configPath,
initialPrompt,
resume,
additionalRules,
}) => {
// Track current assistant configuration state
const [assistant, setAssistant] = useState(initialAssistant);
@ -109,6 +111,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
llmApi,
initialPrompt,
resume,
additionalRules,
onShowOrgSelector: () => showOrganizationSelector(),
onShowConfigSelector: () => showConfigSelectorUI(),
onLoginPrompt: handleLoginPrompt,

View file

@ -22,6 +22,7 @@ interface UseChatProps {
llmApi: BaseLlmApi;
initialPrompt?: string;
resume?: boolean;
additionalRules?: string[];
onShowOrgSelector: () => void;
onShowConfigSelector: () => void;
onLoginPrompt?: (promptText: string) => Promise<string>;
@ -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 }]
: [];

View file

@ -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 };
}
}

9
test-rule.md Normal file
View file

@ -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