This commit is contained in:
Nate 2025-07-16 11:17:30 -07:00
commit 46ba25f1c1
10 changed files with 323 additions and 107 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

@ -1,5 +1,5 @@
import { Box, Text } from "ink";
import React, { useEffect, useState } from "react";
import React, { useEffect, useState, useRef } from "react";
import { glob } from "glob";
interface FileSearchUIProps {
@ -14,6 +14,11 @@ interface FileItem {
displayName: string;
}
// Cache for file search results
const fileCache = new Map<string, FileItem[]>();
let allFiles: FileItem[] = [];
let cacheInitialized = false;
const FileSearchUI: React.FC<FileSearchUIProps> = ({
filter,
selectedIndex,
@ -22,28 +27,38 @@ const FileSearchUI: React.FC<FileSearchUIProps> = ({
}) => {
const [files, setFiles] = useState<FileItem[]>([]);
const [isLoading, setIsLoading] = useState(false);
const initializingRef = useRef(false);
useEffect(() => {
const searchFiles = async () => {
setIsLoading(true);
try {
// Search for files matching the filter
const patterns = [
"**/*.{ts,tsx,js,jsx,py,java,cpp,c,h,hpp,cs,go,rs,rb,php,swift,kt,scala,clj,hs,ml,sh,md,json,yaml,yml,xml,html,css,scss,sass,less,sql,r,m,mm,pl,lua,dart,jl,ex,exs,elm,fs,fsx,ml,mli,v,sv,vhd,vhdl,asm,s,S,f,f90,f95,f03,f08,for,ftn,fpp,F,F90,F95,F03,F08,FOR,FTN,FPP,ada,adb,ads,pas,pp,inc,lpr,dpr,dfm,fmx,lfm,lrs,lpi,lpk,lps,lrt,cfg,conf,config,toml,ini,properties,env,dockerfile,Dockerfile,makefile,Makefile,CMakeLists.txt,BUILD,WORKSPACE,bzl,bazel,gradle,pom.xml,package.json,Cargo.toml,requirements.txt,setup.py,pyproject.toml,composer.json,Gemfile,Podfile,Package.swift,project.pbxproj,*.xcodeproj,*.xcworkspace,*.sln,*.csproj,*.vbproj,*.fsproj,*.vcxproj,*.vcproj,*.dsp,*.dsw,*.pro,*.pri,*.qbs,*.cmake,*.am,*.in,*.m4,*.ac,*.mk,*.mak,*.ninja,*.gyp,*.gypi,*.gn,*.gni,*.bp,*.mm,*.pch,*.plist,*.entitlements,*.storyboard,*.xib,*.nib,*.strings,*.stringsdict,*.lproj,*.bundle,*.framework,*.dylib,*.so,*.dll,*.lib,*.a,*.o,*.obj,*.exe,*.app,*.deb,*.rpm,*.dmg,*.pkg,*.msi,*.tar.gz,*.tgz,*.tar.bz2,*.tbz2,*.tar.xz,*.txz,*.zip,*.7z,*.rar,*.iso,*.img,*.bin,*.hex,*.elf,*.out,*.com,*.bat,*.cmd,*.ps1,*.psm1,*.psd1,*.ps1xml,*.pssc,*.psrc,*.cdxml}",
"**/*.txt",
"**/*.log",
"**/README*",
"**/LICENSE*",
"**/CHANGELOG*",
"**/CONTRIBUTING*",
"**/.gitignore",
"**/.env*",
];
// Initialize cache once
const initializeCache = async () => {
if (cacheInitialized || initializingRef.current) {
return;
}
initializingRef.current = true;
try {
// Use a single, more efficient pattern
const patterns = [
"**/*.{ts,tsx,js,jsx,py,java,cpp,c,h,hpp,cs,go,rs,rb,php,swift,kt,scala,md,json,yaml,yml,xml,html,css,scss,sass,less,sql,sh,dockerfile,makefile,cmake,gradle,toml,ini,env,txt,log}",
"**/README*",
"**/LICENSE*",
"**/CHANGELOG*",
"**/package.json",
"**/Cargo.toml",
"**/pyproject.toml",
"**/composer.json",
"**/Gemfile",
"**/.gitignore",
"**/.env*",
];
const allFiles: string[] = [];
for (const pattern of patterns) {
const matches = await glob(pattern, {
const allMatches: string[] = [];
// Use Promise.all for parallel glob searches
const results = await Promise.all(
patterns.map(pattern =>
glob(pattern, {
ignore: [
"**/node_modules/**",
"**/dist/**",
@ -90,81 +105,116 @@ const FileSearchUI: React.FC<FileSearchUIProps> = ({
],
dot: true,
absolute: false,
});
allFiles.push(...matches);
}
})
)
);
// Remove duplicates and sort
const uniqueFiles = [...new Set(allFiles)];
// Flatten and deduplicate results
for (const matches of results) {
// Handle case where glob might return undefined
if (matches) {
allMatches.push(...matches);
}
}
const uniqueFiles = [...new Set(allMatches)];
allFiles = uniqueFiles.map((path) => ({
path,
displayName: path,
}));
cacheInitialized = true;
} catch (error) {
console.error("Error initializing file cache:", error);
} finally {
initializingRef.current = false;
}
};
// Filter files from cache
const filterFiles = (filterText: string): FileItem[] => {
if (!cacheInitialized) {
return [];
}
if (filterText.length === 0) {
// Show most recently modified files when no filter
return allFiles
.sort((a, b) => {
const aFileName = a.path.split('/').pop() || a.path;
const bFileName = b.path.split('/').pop() || b.path;
return aFileName.localeCompare(bFileName);
})
.slice(0, 10);
}
const lowerFilter = filterText.toLowerCase();
// Check cache first
const cacheKey = lowerFilter;
if (fileCache.has(cacheKey)) {
return fileCache.get(cacheKey)!;
}
const filteredFiles = allFiles
.filter((file) => {
return (
file.displayName.toLowerCase().includes(lowerFilter) ||
file.path.toLowerCase().includes(lowerFilter)
);
})
.sort((a, b) => {
const aFileName = a.path.split('/').pop() || a.path;
const bFileName = b.path.split('/').pop() || b.path;
const fileItems: FileItem[] = uniqueFiles.map((path) => {
// Show the full path from workspace root
const displayName = path;
return {
path,
displayName,
};
});
// Prioritize exact matches in file name
const aNameMatch = aFileName.toLowerCase().includes(lowerFilter);
const bNameMatch = bFileName.toLowerCase().includes(lowerFilter);
if (aNameMatch && !bNameMatch) return -1;
if (!aNameMatch && bNameMatch) return 1;
// Then prioritize files that start with the filter
const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter);
const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter);
if (aStartsWith && !bStartsWith) return -1;
if (!aStartsWith && bStartsWith) return 1;
// Finally, sort by file name
return aFileName.localeCompare(bFileName);
})
.slice(0, 10);
// Filter files based on the current filter
const filteredFiles = fileItems
.filter((file) => {
if (filter.length === 0) {
return true; // Show all files when no filter
}
const lowerFilter = filter.toLowerCase();
return (
file.displayName.toLowerCase().includes(lowerFilter) ||
file.path.toLowerCase().includes(lowerFilter)
);
})
.sort((a, b) => {
if (filter.length === 0) {
// When no filter, sort by file name (not full path)
const aFileName = a.path.split('/').pop() || a.path;
const bFileName = b.path.split('/').pop() || b.path;
return aFileName.localeCompare(bFileName);
}
const lowerFilter = filter.toLowerCase();
// Get file names for comparison
const aFileName = a.path.split('/').pop() || a.path;
const bFileName = b.path.split('/').pop() || b.path;
// Prioritize exact matches in file name
const aNameMatch = aFileName.toLowerCase().includes(lowerFilter);
const bNameMatch = bFileName.toLowerCase().includes(lowerFilter);
if (aNameMatch && !bNameMatch) return -1;
if (!aNameMatch && bNameMatch) return 1;
// Then prioritize files that start with the filter
const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter);
const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter);
if (aStartsWith && !bStartsWith) return -1;
if (!aStartsWith && bStartsWith) return 1;
// Finally, sort by file name
return aFileName.localeCompare(bFileName);
})
.slice(0, 10); // Limit to 10 results for screen space
// Cache the result
fileCache.set(cacheKey, filteredFiles);
// Limit cache size
if (fileCache.size > 100) {
const firstKey = fileCache.keys().next().value;
if (firstKey) {
fileCache.delete(firstKey);
}
}
setFiles(filteredFiles);
if (onFilesUpdated) {
onFilesUpdated(filteredFiles);
}
} catch (error) {
console.error("Error searching files:", error);
setFiles([]);
if (onFilesUpdated) {
onFilesUpdated([]);
}
} finally {
return filteredFiles;
};
useEffect(() => {
const searchFiles = async () => {
if (!cacheInitialized) {
setIsLoading(true);
await initializeCache();
setIsLoading(false);
}
const filteredFiles = filterFiles(filter);
setFiles(filteredFiles);
if (onFilesUpdated) {
onFilesUpdated(filteredFiles);
}
};
searchFiles();
@ -173,7 +223,7 @@ const FileSearchUI: React.FC<FileSearchUIProps> = ({
if (isLoading) {
return (
<Box paddingX={1} marginX={1} marginBottom={1}>
<Text color="gray">Searching files...</Text>
<Text color="gray">Indexing files...</Text>
</Box>
);
}

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