gemini-executor.ts•5.55 kB
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
export interface GeminiOptions {
/** The prompt to send to Gemini */
prompt: string;
/** Working directory for context */
workingDir: string;
/** Maximum response tokens */
maxTokens?: number;
}
export interface GeminiResult {
response: string;
error?: string;
tokenUsage?: {
promptTokens?: number;
responseTokens?: number;
};
}
/**
* Executes Gemini CLI with the provided prompt
*/
export async function executeGemini(options: GeminiOptions): Promise<GeminiResult> {
try {
// Escape quotes and special characters in the prompt
const escapedPrompt = options.prompt
.replace(/"/g, '\\"')
.replace(/\$/g, '\\$')
.replace(/`/g, '\\`');
const command = `gemini "${escapedPrompt}"`;
console.log(`Executing Gemini CLI in: ${options.workingDir}`);
console.log(`Prompt length: ${options.prompt.length} characters`);
const { stdout, stderr } = await execAsync(command, {
cwd: options.workingDir,
maxBuffer: 10 * 1024 * 1024, // 10MB buffer for large responses
timeout: 120000, // 2 minute timeout
});
if (stderr && !stderr.includes('Info:') && !stderr.includes('Using')) {
console.warn('Gemini CLI stderr:', stderr);
}
return {
response: stdout.trim(),
};
} catch (error) {
console.error('Error executing Gemini CLI:', error);
return {
response: '',
error: error instanceof Error ? error.message : 'Unknown error occurred',
};
}
}
/**
* Executes comprehensive codebase review using Gemini
*/
export async function executeComprehensiveReview(
codebaseContent: string,
workingDir: string
): Promise<GeminiResult> {
const prompt = `You are a senior software architect conducting a comprehensive codebase review. Analyze this complete codebase and provide detailed insights.
## Analysis Framework
Provide a structured analysis covering:
### 1. Architecture Overview
- High-level architectural patterns and design principles
- Framework choices and their appropriateness
- Overall system structure and organization
- Integration patterns and external dependencies
### 2. Code Quality Assessment
- Code organization and maintainability
- Consistency of coding patterns and conventions
- Technical debt identification and impact assessment
- Error handling and logging practices
### 3. Security Analysis
- Potential security vulnerabilities
- Authentication and authorization patterns
- Data handling and privacy considerations
- Security best practices compliance
### 4. Performance Considerations
- Performance bottlenecks and optimization opportunities
- Resource usage patterns
- Caching strategies and database optimization
- Frontend performance (if applicable)
### 5. Testing Strategy
- Test coverage and quality
- Testing patterns and practices
- Areas requiring additional testing
- Test automation opportunities
### 6. Refactoring Recommendations
- Priority improvements ranked by impact and effort
- Specific code areas requiring attention
- Architectural improvements and modernization opportunities
- Documentation and maintenance improvements
## Codebase Context
${codebaseContent}
## Instructions
Please provide actionable insights with specific examples and recommendations. Focus on high-impact improvements that will enhance maintainability, performance, and security.`;
return executeGemini({
prompt,
workingDir,
});
}
/**
* Executes targeted analysis on specific components using Gemini
*/
export async function executeTargetedAnalysis(
targetedContent: string,
targetPaths: string[],
workingDir: string
): Promise<GeminiResult> {
const pathsList = targetPaths.join(', ');
const prompt = `You are analyzing specific components of a codebase. Focus your analysis on the provided files/folders and their interactions with the broader system.
## Analysis Target
Files/Folders: ${pathsList}
## Analysis Framework
Provide focused insights covering:
### 1. Component Purpose & Responsibility
- What these files/modules accomplish
- Single Responsibility Principle adherence
- Clear separation of concerns
### 2. Dependencies & Integration
- How these components connect to other parts of the system
- Coupling analysis (tight vs loose coupling)
- Interface design and API patterns
- External dependencies and their management
### 3. Code Quality & Patterns
- Specific code quality issues in these components
- Design patterns usage and appropriateness
- Naming conventions and code readability
- Error handling within these components
### 4. Testing Coverage
- Test gaps specific to these components
- Testing recommendations and priorities
- Mock/stub requirements for isolated testing
- Integration test considerations
### 5. Performance Impact
- Performance characteristics of these components
- Bottlenecks or optimization opportunities
- Resource usage patterns
- Caching opportunities
### 6. Refactoring Priorities
- Specific improvements ranked by impact for these components
- Breaking change considerations
- Migration strategies if applicable
- Backward compatibility requirements
## Component Code Context
${targetedContent}
## Instructions
Focus specifically on the provided components while considering their role in the larger system. Provide concrete, actionable recommendations with examples where possible.`;
return executeGemini({
prompt,
workingDir,
});
}