Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
584 changes: 584 additions & 0 deletions CODE_QUALITY_ANALYSIS.md

Large diffs are not rendered by default.

25 changes: 23 additions & 2 deletions src/cli/automation/agents/agent-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ export class AgentRouter {
averageRoutingTime: 0,
agentUtilization: new Map(),
}
// FIXED: Store intervals for proper cleanup
private cleanupInterval?: NodeJS.Timeout
private metricsInterval?: NodeJS.Timeout

constructor() {
this.eventBus = EventBus.getInstance()
Expand Down Expand Up @@ -552,20 +555,38 @@ export class AgentRouter {
* Setup performance optimizations
*/
private setupPerformanceOptimizations(): void {
// FIXED: Store interval references for cleanup
// Periodic cleanup of completed routes
setInterval(
this.cleanupInterval = setInterval(
() => {
this.cleanupCompletedRoutes()
},
5 * 60 * 1000
) // Every 5 minutes

// Performance metrics optimization
setInterval(() => {
this.metricsInterval = setInterval(() => {
this.optimizeAgentUtilization()
}, 30 * 1000) // Every 30 seconds
}

/**
* FIXED: Dispose method to clean up resources
*/
public dispose(): void {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval)
this.cleanupInterval = undefined
}
if (this.metricsInterval) {
clearInterval(this.metricsInterval)
this.metricsInterval = undefined
}
this.agents.clear()
this.taskQueue = []
this.activeRoutes.clear()
}

/**
* Clean up completed routes and old metrics
*/
Expand Down
17 changes: 16 additions & 1 deletion src/cli/browser/browser-container-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export class BrowserContainerManager extends ContainerManager {
private readonly baseNoVNCPort = 6080
private readonly basePlaywrightPort = 9222
private readonly baseVNCPort = 5900
// FIXED: Store cleanup interval for proper disposal
private cleanupInterval?: NodeJS.Timeout

constructor() {
super()
Expand Down Expand Up @@ -543,11 +545,24 @@ export class BrowserContainerManager extends ContainerManager {
advancedUI.logFunctionUpdate('info', `Container stopped: ${containerId.slice(0, 12)}`, '⏹️')
})

// FIXED: Store interval reference for cleanup
// Periodic cleanup of inactive containers
setInterval(() => {
this.cleanupInterval = setInterval(() => {
this.cleanupInactiveBrowserContainers()
}, 300000) // Every 5 minutes
}

/**
* FIXED: Dispose method to clean up resources
*/
public dispose(): void {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval)
this.cleanupInterval = undefined
}
this.activeBrowserContainers.clear()
this.removeAllListeners()
}
}

// Type definitions
Expand Down
9 changes: 9 additions & 0 deletions src/cli/chat/chat-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,15 @@ export class ChatManager {
currentSessionMessages: this.currentSession?.messages.length || 0,
}
}

/**
* FIXED: Added dispose method to clean up resources
* Prevents memory leaks from LRU cache and session data
*/
dispose(): void {
this.sessions.clear()
this.currentSession = null
}
}

export const chatManager = new ChatManager()
18 changes: 17 additions & 1 deletion src/cli/core/enhanced-tool-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ export class EnhancedToolRouter extends ToolRouter {
private projectContextCache: ProjectContext | null = null
private lastAnalysisTime: number = 0
private smartSuggestionCache: Map<string, EnhancedToolRecommendation[]> = new Map()
// FIXED: Store cleanup interval for proper disposal
private cleanupInterval?: NodeJS.Timeout

constructor() {
super()
Expand All @@ -65,8 +67,9 @@ export class EnhancedToolRouter extends ToolRouter {
// Initialize user pattern learning
this.loadUserPatterns()

// FIXED: Store interval reference for cleanup
// Set up cache cleanup
setInterval(() => this.cleanupCache(), 5 * 60 * 1000) // 5 minutes
this.cleanupInterval = setInterval(() => this.cleanupCache(), 5 * 60 * 1000) // 5 minutes
}

/**
Expand Down Expand Up @@ -635,6 +638,19 @@ export class EnhancedToolRouter extends ToolRouter {
toKeep.forEach(([key, value]) => this.smartSuggestionCache.set(key, value))
}
}

/**
* FIXED: Dispose method to clean up resources
*/
public dispose(): void {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval)
this.cleanupInterval = undefined
}
this.smartSuggestionCache.clear()
this.userPatterns.clear()
this.recentCommands = []
}
}

export const enhancedToolRouter = new EnhancedToolRouter()
17 changes: 16 additions & 1 deletion src/cli/providers/memory/mem0-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ export class Mem0Provider extends EventEmitter {
private isInitialized = false
private memoriesDir: string
private currentUserId: string | null = null
// FIXED: Store cleanup interval for proper disposal
private cleanupInterval?: NodeJS.Timeout

constructor() {
super()
Expand Down Expand Up @@ -708,15 +710,28 @@ export class Mem0Provider extends EventEmitter {
}

private setupAutoCleanup(): void {
// FIXED: Store interval reference for cleanup
// Run cleanup every hour
setInterval(
this.cleanupInterval = setInterval(
async () => {
await this.cleanupOldMemories()
},
60 * 60 * 1000
)
}

/**
* FIXED: Dispose method to clean up resources
*/
public dispose(): void {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval)
this.cleanupInterval = undefined
}
this.memories.clear()
this.removeAllListeners()
}

private async cleanupOldMemories(): Promise<void> {
const cutoffTime = Date.now() - this.config.importance_decay_days * 24 * 60 * 60 * 1000
let cleanedCount = 0
Expand Down
15 changes: 9 additions & 6 deletions src/cli/services/agent-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -447,8 +447,9 @@ export class AgentService extends EventEmitter {
// Attempt to close the generator gracefully
try {
await (generator as any)?.return?.()
} catch {
/* ignore */
} catch (err: any) {
// FIXED: Log generator cleanup errors for debugging
console.debug?.('Generator cleanup during cancel:', err?.message || 'unknown')
}
throw new Error('Cancelled by user')
}
Expand Down Expand Up @@ -584,8 +585,9 @@ export class AgentService extends EventEmitter {
if (gen && typeof (gen as any).return === 'function') {
try {
;(gen as any).return()
} catch {
/* ignore */
} catch (err: any) {
// FIXED: Log generator cleanup errors for debugging
console.debug?.('Generator return cleanup:', err?.message || 'unknown')
}
}
console.log(chalk.yellow(`⏹️ Cancellation requested for task ${taskId}`))
Expand Down Expand Up @@ -627,8 +629,9 @@ export class AgentService extends EventEmitter {
this.activeTasks.clear()
this.taskQueue = []
this.removeAllListeners()
} catch {
// ignore
} catch (err: any) {
// FIXED: Log instead of silently ignoring dispose errors
console.error('AgentService dispose warning:', err?.message || 'unknown')
}
}

Expand Down
16 changes: 15 additions & 1 deletion src/cli/services/ai-completion-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,13 @@ export class AICompletionService {
private readonly cacheExpiryMs = 5 * 60 * 1000 // 5 minutes
private readonly maxCacheSize = 100
private readonly completionTimeout = 3000 // 3 seconds max for AI completion
// FIXED: Store interval for cleanup
private cleanupInterval?: NodeJS.Timeout

constructor() {
// Clear expired cache entries periodically
setInterval(() => this.cleanCache(), 60 * 1000) // Every minute
// FIXED: Store interval reference for proper cleanup
this.cleanupInterval = setInterval(() => this.cleanCache(), 60 * 1000) // Every minute
}

/**
Expand Down Expand Up @@ -493,6 +496,17 @@ Provide 3-8 most relevant completions, ranked by relevance and confidence.`
public clearCache(): void {
this.cache.clear()
}

/**
* FIXED: Dispose method to clean up interval
*/
public dispose(): void {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval)
this.cleanupInterval = undefined
}
this.cache.clear()
}
}

export const aiCompletionService = new AICompletionService()
Loading
Loading