@stackmemoryai/stackmemory 0.5.49 → 0.5.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +17 -3
  2. package/dist/cli/claude-sm.js +246 -5
  3. package/dist/cli/claude-sm.js.map +3 -3
  4. package/dist/cli/commands/handoff.js +27 -12
  5. package/dist/cli/commands/handoff.js.map +2 -2
  6. package/dist/cli/commands/sweep.js +190 -421
  7. package/dist/cli/commands/sweep.js.map +3 -3
  8. package/dist/cli/index.js +10 -2
  9. package/dist/cli/index.js.map +2 -2
  10. package/dist/core/config/feature-flags.js +7 -1
  11. package/dist/core/config/feature-flags.js.map +2 -2
  12. package/dist/core/context/enhanced-rehydration.js +355 -9
  13. package/dist/core/context/enhanced-rehydration.js.map +3 -3
  14. package/dist/core/context/shared-context-layer.js +229 -0
  15. package/dist/core/context/shared-context-layer.js.map +2 -2
  16. package/dist/features/sweep/index.js +20 -0
  17. package/dist/features/sweep/index.js.map +7 -0
  18. package/dist/features/sweep/prediction-client.js +155 -0
  19. package/dist/features/sweep/prediction-client.js.map +7 -0
  20. package/dist/features/sweep/prompt-builder.js +85 -0
  21. package/dist/features/sweep/prompt-builder.js.map +7 -0
  22. package/dist/features/sweep/pty-wrapper.js +171 -0
  23. package/dist/features/sweep/pty-wrapper.js.map +7 -0
  24. package/dist/features/sweep/state-watcher.js +87 -0
  25. package/dist/features/sweep/state-watcher.js.map +7 -0
  26. package/dist/features/sweep/status-bar.js +88 -0
  27. package/dist/features/sweep/status-bar.js.map +7 -0
  28. package/dist/features/sweep/sweep-server-manager.js +226 -0
  29. package/dist/features/sweep/sweep-server-manager.js.map +7 -0
  30. package/dist/features/sweep/tab-interceptor.js +38 -0
  31. package/dist/features/sweep/tab-interceptor.js.map +7 -0
  32. package/dist/features/sweep/types.js +18 -0
  33. package/dist/features/sweep/types.js.map +7 -0
  34. package/dist/integrations/claude-code/lifecycle-hooks.js +3 -3
  35. package/dist/integrations/claude-code/lifecycle-hooks.js.map +1 -1
  36. package/package.json +1 -1
  37. package/scripts/auto-handoff.sh +1 -1
  38. package/scripts/claude-sm-autostart.js +174 -132
  39. package/scripts/setup-claude-integration.js +14 -10
  40. package/scripts/stackmemory-auto-handoff.sh +3 -3
  41. package/scripts/test-session-handoff.sh +2 -2
  42. package/scripts/test-setup-e2e.sh +154 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/core/context/enhanced-rehydration.ts"],
4
- "sourcesContent": ["/**\n * Enhanced Context Rehydration System\n * Addresses compact summary limitations with rich context recovery\n */\n\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport { logger } from '../monitoring/logger.js';\nimport { FrameManager } from './index.js';\nimport { CompactionHandler } from './compaction-handler.js';\n\nexport interface FileSnapshot {\n path: string;\n content: string;\n size: number;\n lastModified: number;\n hash: string; // Quick change detection\n contextTags: string[]; // e.g., ['migration', 'pipedream', 'hubspot']\n}\n\nexport interface StackTrace {\n error_message: string;\n stack_frames: string[];\n file_path?: string;\n line_number?: number;\n function_name?: string;\n timestamp: number;\n context: string; // What was being done when error occurred\n resolution_attempted?: string[];\n resolution_status: 'pending' | 'resolved' | 'workaround' | 'blocked';\n}\n\nexport interface ConversationContext {\n timestamp: number;\n reasoning: string[];\n decisions_made: string[];\n next_steps: string[];\n user_preferences: Record<string, any>;\n pain_points: string[];\n stack_traces: StackTrace[];\n error_patterns: string[]; // Recurring error types\n}\n\nexport interface ProjectMapping {\n file_relationships: Record<string, string[]>; // file -> related files\n workflow_sequences: string[][]; // sequences of files in workflows\n key_directories: string[];\n entry_points: string[];\n configuration_files: string[];\n}\n\nexport interface RehydrationContext {\n session_id: string;\n compact_detected_at: number;\n pre_compact_state: {\n file_snapshots: FileSnapshot[];\n conversation_context: ConversationContext;\n project_mapping: ProjectMapping;\n active_workflows: string[];\n current_focus: string;\n };\n recovery_anchors: string[];\n}\n\nexport class EnhancedRehydrationManager {\n private frameManager: FrameManager;\n private compactionHandler: CompactionHandler;\n private snapshotThreshold = 10; // Take snapshot every N significant events\n private eventCount = 0;\n private rehydrationStorage = new Map<string, RehydrationContext>();\n\n constructor(frameManager: FrameManager, compactionHandler: CompactionHandler) {\n this.frameManager = frameManager;\n this.compactionHandler = compactionHandler;\n this.setupCompactDetection();\n this.initializeStackTraceStorage();\n }\n\n /**\n * Initialize dedicated stack trace storage in database\n */\n private initializeStackTraceStorage(): void {\n try {\n const db = (this.frameManager as any).db; // Access the underlying database\n \n // Create stack_traces table for persistent storage\n db.exec(`\n CREATE TABLE IF NOT EXISTS stack_traces (\n trace_id TEXT PRIMARY KEY,\n frame_id TEXT,\n project_id TEXT NOT NULL,\n error_message TEXT NOT NULL,\n stack_frames TEXT NOT NULL,\n file_path TEXT,\n line_number INTEGER,\n function_name TEXT,\n context TEXT,\n resolution_attempted TEXT,\n resolution_status TEXT NOT NULL DEFAULT 'pending',\n error_type TEXT,\n error_severity TEXT DEFAULT 'medium',\n created_at INTEGER DEFAULT (unixepoch()),\n updated_at INTEGER DEFAULT (unixepoch()),\n FOREIGN KEY(frame_id) REFERENCES frames(frame_id)\n );\n\n CREATE INDEX IF NOT EXISTS idx_stack_traces_frame ON stack_traces(frame_id);\n CREATE INDEX IF NOT EXISTS idx_stack_traces_status ON stack_traces(resolution_status);\n CREATE INDEX IF NOT EXISTS idx_stack_traces_type ON stack_traces(error_type);\n CREATE INDEX IF NOT EXISTS idx_stack_traces_severity ON stack_traces(error_severity);\n CREATE INDEX IF NOT EXISTS idx_stack_traces_created ON stack_traces(created_at);\n `);\n \n logger.info('Stack trace storage initialized');\n } catch (error) {\n logger.error('Failed to initialize stack trace storage:', error);\n }\n }\n\n /**\n * Set up automatic compact detection and recovery\n */\n private setupCompactDetection(): void {\n // Monitor for compact indicators in new frames\n setInterval(() => this.checkForCompactionEvent(), 30000); // Check every 30s\n }\n\n /**\n * Enhanced file content snapshot with context\n */\n async captureFileSnapshot(filePath: string, contextTags: string[] = []): Promise<FileSnapshot | null> {\n try {\n const stats = await fs.stat(filePath);\n const content = await fs.readFile(filePath, 'utf8');\n \n // Simple hash for change detection\n const hash = this.simpleHash(content);\n\n return {\n path: filePath,\n content: content,\n size: stats.size,\n lastModified: stats.mtimeMs,\n hash: hash,\n contextTags: contextTags\n };\n } catch (error) {\n logger.warn(`Failed to capture snapshot for ${filePath}:`, error);\n return null;\n }\n }\n\n /**\n * Capture conversation reasoning and decisions including stack traces\n */\n captureConversationContext(\n reasoning: string[],\n decisions: string[],\n nextSteps: string[] = [],\n userPrefs: Record<string, any> = {},\n painPoints: string[] = [],\n stackTraces: StackTrace[] = [],\n errorPatterns: string[] = []\n ): ConversationContext {\n return {\n timestamp: Date.now(),\n reasoning: reasoning,\n decisions_made: decisions,\n next_steps: nextSteps,\n user_preferences: userPrefs,\n pain_points: painPoints,\n stack_traces: stackTraces,\n error_patterns: errorPatterns\n };\n }\n\n /**\n * Capture stack trace from error with context and store in database\n */\n captureStackTrace(\n error: Error | string,\n context: string,\n filePath?: string,\n resolutionAttempts: string[] = [],\n frameId?: string\n ): StackTrace {\n const errorMessage = typeof error === 'string' ? error : error.message;\n const stackFrames = typeof error === 'string' ? [] : (error.stack?.split('\\n') || []);\n\n // Extract file path and line number from stack if not provided\n let extractedFilePath = filePath;\n let lineNumber: number | undefined;\n let functionName: string | undefined;\n\n if (stackFrames.length > 0) {\n const firstFrame = stackFrames.find(frame => frame.includes('at '));\n if (firstFrame) {\n const match = firstFrame.match(/at (.+?) \\((.+):(\\d+):(\\d+)\\)/);\n if (match) {\n functionName = match[1];\n extractedFilePath = extractedFilePath || match[2];\n lineNumber = parseInt(match[3]);\n }\n }\n }\n\n const stackTrace: StackTrace = {\n error_message: errorMessage,\n stack_frames: stackFrames,\n file_path: extractedFilePath,\n line_number: lineNumber,\n function_name: functionName,\n timestamp: Date.now(),\n context: context,\n resolution_attempted: resolutionAttempts,\n resolution_status: 'pending'\n };\n\n // Store in database\n this.storeStackTrace(stackTrace, frameId);\n\n return stackTrace;\n }\n\n /**\n * Store stack trace in database\n */\n private storeStackTrace(stackTrace: StackTrace, frameId?: string): string {\n try {\n const db = (this.frameManager as any).db;\n const traceId = this.generateTraceId();\n const currentFrameId = frameId || this.frameManager.getCurrentFrameId();\n \n // Determine error type and severity\n const errorType = this.extractErrorType(stackTrace.error_message);\n const severity = this.determineErrorSeverity(stackTrace);\n\n const stmt = db.prepare(`\n INSERT INTO stack_traces (\n trace_id, frame_id, project_id, error_message, stack_frames,\n file_path, line_number, function_name, context, resolution_attempted,\n resolution_status, error_type, error_severity\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n stmt.run(\n traceId,\n currentFrameId,\n (this.frameManager as any).projectId,\n stackTrace.error_message,\n JSON.stringify(stackTrace.stack_frames),\n stackTrace.file_path,\n stackTrace.line_number,\n stackTrace.function_name,\n stackTrace.context,\n JSON.stringify(stackTrace.resolution_attempted),\n stackTrace.resolution_status,\n errorType,\n severity\n );\n\n logger.info(`Stored stack trace ${traceId} for frame ${currentFrameId}`);\n return traceId;\n } catch (error) {\n logger.error('Failed to store stack trace:', error);\n return '';\n }\n }\n\n /**\n * Retrieve stack traces from database\n */\n public getStackTraces(frameId?: string, limit: number = 50): StackTrace[] {\n try {\n const db = (this.frameManager as any).db;\n const traces: StackTrace[] = [];\n\n let query: string;\n let params: any[];\n\n if (frameId) {\n query = `\n SELECT * FROM stack_traces \n WHERE frame_id = ? \n ORDER BY created_at DESC \n LIMIT ?\n `;\n params = [frameId, limit];\n } else {\n query = `\n SELECT * FROM stack_traces \n WHERE project_id = ? \n ORDER BY created_at DESC \n LIMIT ?\n `;\n params = [(this.frameManager as any).projectId, limit];\n }\n\n const rows = db.prepare(query).all(...params);\n\n for (const row of rows) {\n traces.push({\n error_message: row.error_message,\n stack_frames: JSON.parse(row.stack_frames || '[]'),\n file_path: row.file_path,\n line_number: row.line_number,\n function_name: row.function_name,\n timestamp: row.created_at * 1000, // Convert from unix to JS timestamp\n context: row.context,\n resolution_attempted: JSON.parse(row.resolution_attempted || '[]'),\n resolution_status: row.resolution_status\n });\n }\n\n return traces;\n } catch (error) {\n logger.error('Failed to retrieve stack traces:', error);\n return [];\n }\n }\n\n /**\n * Update stack trace resolution status\n */\n public updateStackTraceStatus(\n traceId: string,\n status: StackTrace['resolution_status'],\n resolutionAttempts?: string[]\n ): boolean {\n try {\n const db = (this.frameManager as any).db;\n \n const stmt = db.prepare(`\n UPDATE stack_traces \n SET resolution_status = ?, resolution_attempted = ?, updated_at = unixepoch()\n WHERE trace_id = ?\n `);\n\n const result = stmt.run(\n status,\n resolutionAttempts ? JSON.stringify(resolutionAttempts) : undefined,\n traceId\n );\n\n return result.changes > 0;\n } catch (error) {\n logger.error('Failed to update stack trace status:', error);\n return false;\n }\n }\n\n /**\n * Helper methods for stack trace processing\n */\n private generateTraceId(): string {\n return `trace_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n private extractErrorType(errorMessage: string): string {\n const typeMatch = errorMessage.match(/^(\\w+Error?):/);\n return typeMatch ? typeMatch[1] : 'Unknown';\n }\n\n private determineErrorSeverity(stackTrace: StackTrace): string {\n const message = stackTrace.error_message.toLowerCase();\n \n if (message.includes('critical') || message.includes('fatal') || message.includes('cannot read properties')) {\n return 'high';\n } else if (message.includes('warning') || message.includes('deprecated')) {\n return 'low';\n } else {\n return 'medium';\n }\n }\n\n /**\n * Auto-detect project structure and relationships\n */\n async analyzeProjectMapping(workingDir: string): Promise<ProjectMapping> {\n const mapping: ProjectMapping = {\n file_relationships: {},\n workflow_sequences: [],\n key_directories: [],\n entry_points: [],\n configuration_files: []\n };\n\n try {\n // Find configuration files\n const configPatterns = [\n 'package.json', 'tsconfig.json', '.env', 'docker-compose.yml',\n '*.config.js', '*.config.ts', 'Dockerfile', 'README.md'\n ];\n\n // Analyze directory structure\n const files = await this.getDirectoryFiles(workingDir);\n \n for (const file of files) {\n const ext = path.extname(file);\n const basename = path.basename(file);\n \n // Identify configuration files\n if (configPatterns.some(pattern => \n pattern.includes('*') ? basename.includes(pattern.replace('*', '')) : basename === pattern\n )) {\n mapping.configuration_files.push(file);\n }\n\n // Identify entry points\n if (basename === 'index.js' || basename === 'index.ts' || basename === 'main.js') {\n mapping.entry_points.push(file);\n }\n\n // Find related files based on naming patterns\n const filePrefix = basename.split('.')[0];\n const relatedFiles = files.filter(f => \n f !== file && path.basename(f).startsWith(filePrefix)\n );\n if (relatedFiles.length > 0) {\n mapping.file_relationships[file] = relatedFiles;\n }\n }\n\n // Identify key directories\n const dirs = files.map(f => path.dirname(f)).filter((v, i, a) => a.indexOf(v) === i);\n mapping.key_directories = dirs.filter(dir => \n ['src', 'lib', 'components', 'pages', 'api', 'utils', 'types'].some(key => dir.includes(key))\n );\n\n } catch (error) {\n logger.warn('Failed to analyze project mapping:', error);\n }\n\n return mapping;\n }\n\n /**\n * Create comprehensive rehydration context before compaction\n */\n async createRehydrationCheckpoint(): Promise<string> {\n const sessionId = this.frameManager.getSessionId() || 'unknown';\n const checkpointId = `${sessionId}_${Date.now()}`;\n\n try {\n // Get current working directory\n const workingDir = process.cwd();\n\n // Capture file snapshots for recently modified files\n const fileSnapshots: FileSnapshot[] = [];\n const recentFiles = await this.getRecentlyModifiedFiles(workingDir);\n \n for (const file of recentFiles.slice(0, 20)) { // Limit to 20 most recent\n const snapshot = await this.captureFileSnapshot(file, this.inferContextTags(file));\n if (snapshot) {\n fileSnapshots.push(snapshot);\n }\n }\n\n // Capture project mapping\n const projectMapping = await this.analyzeProjectMapping(workingDir);\n\n // Extract conversation context from recent events\n const conversationContext = this.extractConversationContext();\n\n // Create rehydration context\n const rehydrationContext: RehydrationContext = {\n session_id: sessionId,\n compact_detected_at: Date.now(),\n pre_compact_state: {\n file_snapshots: fileSnapshots,\n conversation_context: conversationContext,\n project_mapping: projectMapping,\n active_workflows: this.detectActiveWorkflows(fileSnapshots),\n current_focus: this.inferCurrentFocus(fileSnapshots, conversationContext)\n },\n recovery_anchors: this.createRecoveryAnchors(fileSnapshots, conversationContext)\n };\n\n // Store for later retrieval\n this.rehydrationStorage.set(checkpointId, rehydrationContext);\n\n // Also persist to file system for cross-session recovery\n await this.persistRehydrationContext(checkpointId, rehydrationContext);\n\n logger.info(`Created rehydration checkpoint ${checkpointId} with ${fileSnapshots.length} file snapshots`);\n \n return checkpointId;\n } catch (error) {\n logger.error('Failed to create rehydration checkpoint:', error);\n throw error;\n }\n }\n\n /**\n * Inject rich context after compaction detection\n */\n async rehydrateContext(checkpointId?: string): Promise<boolean> {\n try {\n let context: RehydrationContext | undefined;\n\n if (checkpointId) {\n context = this.rehydrationStorage.get(checkpointId);\n if (!context) {\n context = await this.loadPersistedContext(checkpointId);\n }\n } else {\n // Find most recent context\n context = await this.findMostRecentContext();\n }\n\n if (!context) {\n logger.warn('No rehydration context available');\n return false;\n }\n\n await this.injectRichContext(context);\n return true;\n } catch (error) {\n logger.error('Failed to rehydrate context:', error);\n return false;\n }\n }\n\n /**\n * Inject rich context into current session\n */\n private async injectRichContext(context: RehydrationContext): Promise<void> {\n const frameId = this.frameManager.getCurrentFrameId();\n if (!frameId) {\n logger.warn('No active frame for context injection');\n return;\n }\n\n // Inject file context\n for (const snapshot of context.pre_compact_state.file_snapshots.slice(0, 5)) { // Top 5 files\n this.frameManager.addAnchor(\n 'FACT',\n `File: ${snapshot.path} (${snapshot.contextTags.join(', ')})\\n` +\n `Last modified: ${new Date(snapshot.lastModified).toISOString()}\\n` +\n `Size: ${snapshot.size} bytes\\n` +\n `Content preview: ${this.getContentPreview(snapshot.content)}`,\n 9,\n { \n rehydration: true, \n file_path: snapshot.path,\n context_tags: snapshot.contextTags\n },\n frameId\n );\n }\n\n // Inject conversation context\n const conv = context.pre_compact_state.conversation_context;\n if (conv.decisions_made.length > 0) {\n this.frameManager.addAnchor(\n 'DECISION',\n `Previous decisions: ${conv.decisions_made.join('; ')}`,\n 8,\n { rehydration: true },\n frameId\n );\n }\n\n if (conv.next_steps.length > 0) {\n this.frameManager.addAnchor(\n 'FACT',\n `Next steps identified: ${conv.next_steps.join('; ')}`,\n 7,\n { rehydration: true },\n frameId\n );\n }\n\n // Inject stack trace context\n if (conv.stack_traces.length > 0) {\n for (const trace of conv.stack_traces.slice(0, 3)) { // Top 3 most recent errors\n this.frameManager.addAnchor(\n 'ERROR',\n `Error context: ${trace.error_message}\\n` +\n `Context: ${trace.context}\\n` +\n `File: ${trace.file_path || 'unknown'}${trace.line_number ? `:${trace.line_number}` : ''}\\n` +\n `Function: ${trace.function_name || 'unknown'}\\n` +\n `Status: ${trace.resolution_status}\\n` +\n `Stack preview: ${trace.stack_frames.slice(0, 3).join('\\n')}`,\n 9,\n { \n rehydration: true,\n error_type: trace.error_message.split(':')[0],\n resolution_status: trace.resolution_status,\n file_path: trace.file_path\n },\n frameId\n );\n }\n }\n\n // Inject error patterns\n if (conv.error_patterns.length > 0) {\n this.frameManager.addAnchor(\n 'PATTERN',\n `Recurring error patterns detected: ${conv.error_patterns.join(', ')}`,\n 7,\n { rehydration: true },\n frameId\n );\n }\n\n // Inject project mapping\n const mapping = context.pre_compact_state.project_mapping;\n if (mapping.entry_points.length > 0) {\n this.frameManager.addAnchor(\n 'FACT',\n `Project entry points: ${mapping.entry_points.join(', ')}`,\n 6,\n { rehydration: true },\n frameId\n );\n }\n\n // Inject current focus\n if (context.pre_compact_state.current_focus) {\n this.frameManager.addAnchor(\n 'CONSTRAINT',\n `Previous focus: ${context.pre_compact_state.current_focus}`,\n 8,\n { rehydration: true },\n frameId\n );\n }\n\n logger.info('Rich context injected successfully');\n }\n\n // Helper methods\n private async getDirectoryFiles(dir: string): Promise<string[]> {\n // Implementation to recursively get files\n return []; // Simplified for now\n }\n\n private async getRecentlyModifiedFiles(dir: string): Promise<string[]> {\n // Implementation to get recently modified files\n return []; // Simplified for now\n }\n\n private inferContextTags(filePath: string): string[] {\n const tags: string[] = [];\n const content = filePath.toLowerCase();\n \n if (content.includes('pipeline') || content.includes('migrate')) tags.push('migration');\n if (content.includes('hubspot')) tags.push('hubspot');\n if (content.includes('pipedream')) tags.push('pipedream');\n if (content.includes('test')) tags.push('test');\n if (content.includes('config')) tags.push('configuration');\n \n return tags;\n }\n\n private extractConversationContext(): ConversationContext {\n // Extract from recent frame events\n const recentErrors = this.extractRecentStackTraces();\n const errorPatterns = this.detectErrorPatterns(recentErrors);\n \n return {\n timestamp: Date.now(),\n reasoning: [],\n decisions_made: [],\n next_steps: [],\n user_preferences: {},\n pain_points: [],\n stack_traces: recentErrors,\n error_patterns: errorPatterns\n };\n }\n\n /**\n * Extract recent stack traces from database and frame events\n */\n private extractRecentStackTraces(): StackTrace[] {\n try {\n // Get recent stack traces from database (most reliable source)\n const dbTraces = this.getStackTraces(undefined, 10);\n \n // Also check frame events for additional traces\n const eventTraces = this.extractStackTracesFromFrameEvents();\n \n // Combine and deduplicate\n const allTraces = [...dbTraces, ...eventTraces];\n \n // Remove duplicates based on error message and file path\n const uniqueTraces = allTraces.filter((trace, index, array) => \n array.findIndex(t => \n t.error_message === trace.error_message && \n t.file_path === trace.file_path\n ) === index\n );\n \n // Sort by timestamp (newest first) and return top 5\n return uniqueTraces\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, 5);\n } catch (error) {\n logger.warn('Failed to extract stack traces:', error);\n return [];\n }\n }\n\n /**\n * Extract stack traces from frame events (fallback method)\n */\n private extractStackTracesFromFrameEvents(): StackTrace[] {\n const traces: StackTrace[] = [];\n \n try {\n // Get recent frames and look for error events\n const frames = this.frameManager.getActiveFramePath();\n \n for (const frame of frames.slice(-3)) { // Check last 3 frames\n const frameData = this.frameManager.getFrame(frame.frame_id);\n if (frameData?.events) {\n for (const event of frameData.events) {\n if (event.type === 'error' || event.type === 'exception') {\n const trace = this.parseStackTraceFromEvent(event);\n if (trace) {\n traces.push(trace);\n }\n }\n }\n }\n }\n } catch (error) {\n logger.warn('Failed to extract frame event traces:', error);\n }\n \n return traces;\n }\n\n /**\n * Parse stack trace from frame event\n */\n private parseStackTraceFromEvent(event: any): StackTrace | null {\n try {\n const data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;\n \n return {\n error_message: data.error || data.message || 'Unknown error',\n stack_frames: data.stack ? data.stack.split('\\n') : [],\n file_path: data.file || data.fileName,\n line_number: data.line || data.lineNumber,\n function_name: data.function || data.functionName,\n timestamp: event.timestamp || Date.now(),\n context: data.context || 'Error occurred during frame processing',\n resolution_attempted: data.resolutionAttempts || [],\n resolution_status: data.resolved ? 'resolved' : 'pending'\n };\n } catch (error) {\n return null;\n }\n }\n\n /**\n * Detect recurring error patterns\n */\n private detectErrorPatterns(traces: StackTrace[]): string[] {\n const patterns = new Map<string, number>();\n \n for (const trace of traces) {\n // Extract error type from message\n const errorType = trace.error_message.split(':')[0].trim();\n patterns.set(errorType, (patterns.get(errorType) || 0) + 1);\n }\n \n // Return patterns that occur more than once\n return Array.from(patterns.entries())\n .filter(([, count]) => count > 1)\n .map(([pattern]) => pattern);\n }\n\n private detectActiveWorkflows(snapshots: FileSnapshot[]): string[] {\n const workflows: string[] = [];\n \n for (const snapshot of snapshots) {\n if (snapshot.contextTags.includes('migration')) {\n workflows.push('data_migration');\n }\n if (snapshot.path.includes('test')) {\n workflows.push('testing');\n }\n }\n \n return [...new Set(workflows)];\n }\n\n private inferCurrentFocus(snapshots: FileSnapshot[], context: ConversationContext): string {\n // Analyze recent file activity and conversation to infer focus\n if (snapshots.some(s => s.contextTags.includes('migration'))) {\n return 'Data migration and transformation';\n }\n if (snapshots.some(s => s.path.includes('test'))) {\n return 'Testing and validation';\n }\n return 'Development';\n }\n\n private createRecoveryAnchors(snapshots: FileSnapshot[], context: ConversationContext): string[] {\n const anchors: string[] = [];\n \n // Create anchor points for each significant file\n for (const snapshot of snapshots.slice(0, 3)) {\n anchors.push(`File context: ${snapshot.path} with ${snapshot.contextTags.join(', ')}`);\n }\n \n return anchors;\n }\n\n private async persistRehydrationContext(id: string, context: RehydrationContext): Promise<void> {\n // Implementation to persist context to filesystem\n const contextDir = path.join(process.cwd(), '.stackmemory', 'rehydration');\n await fs.mkdir(contextDir, { recursive: true });\n await fs.writeFile(\n path.join(contextDir, `${id}.json`),\n JSON.stringify(context, null, 2)\n );\n }\n\n private async loadPersistedContext(id: string): Promise<RehydrationContext | undefined> {\n try {\n const contextPath = path.join(process.cwd(), '.stackmemory', 'rehydration', `${id}.json`);\n const content = await fs.readFile(contextPath, 'utf8');\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n }\n\n private async findMostRecentContext(): Promise<RehydrationContext | undefined> {\n // Find most recent persisted context\n return undefined; // Simplified for now\n }\n\n private checkForCompactionEvent(): void {\n // Check if compaction occurred and trigger rehydration\n if (this.compactionHandler.detectCompactionEvent('')) {\n this.rehydrateContext();\n }\n }\n\n private simpleHash(content: string): string {\n let hash = 0;\n for (let i = 0; i < content.length; i++) {\n const char = content.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash.toString(16);\n }\n\n private getContentPreview(content: string, maxLength = 200): string {\n return content.length > maxLength \n ? content.substring(0, maxLength) + '...'\n : content;\n }\n}"],
5
- "mappings": ";;;;AAKA,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAAS,cAAc;AAyDhB,MAAM,2BAA2B;AAAA,EAC9B;AAAA,EACA;AAAA,EACA,oBAAoB;AAAA;AAAA,EACpB,aAAa;AAAA,EACb,qBAAqB,oBAAI,IAAgC;AAAA,EAEjE,YAAY,cAA4B,mBAAsC;AAC5E,SAAK,eAAe;AACpB,SAAK,oBAAoB;AACzB,SAAK,sBAAsB;AAC3B,SAAK,4BAA4B;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA,EAKQ,8BAAoC;AAC1C,QAAI;AACF,YAAM,KAAM,KAAK,aAAqB;AAGtC,SAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAS,MAAM,CAAC;AAAA,IACjC;AAAA,EACF;AAAA,EAEA,MAAc,qBAAqB,IAAqD;AACtF,QAAI;AACF,YAAM,cAAc,KAAK,KAAK,QAAQ,IAAI,GAAG,gBAAgB,eAAe,GAAG,EAAE,OAAO;AACxF,YAAM,UAAU,MAAM,GAAG,SAAS,aAAa,MAAM;AACrD,aAAO,KAAK,MAAM,OAAO;AAAA,IAC3B,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAAA,EAEA,MAAc,wBAAiE;AAE7E,WAAO;AAAA,EACT;AAAA,EAEQ,0BAAgC;AAEtC,QAAI,KAAK,kBAAkB,sBAAsB,EAAE,GAAG;AACpD,WAAK,iBAAiB;AAAA,IACxB;AAAA,EACF;AAAA,EAEQ,WAAW,SAAyB;AAC1C,QAAI,OAAO;AACX,aAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,YAAM,OAAO,QAAQ,WAAW,CAAC;AACjC,cAAS,QAAQ,KAAK,OAAQ;AAC9B,aAAO,OAAO;AAAA,IAChB;AACA,WAAO,KAAK,SAAS,EAAE;AAAA,EACzB;AAAA,EAEQ,kBAAkB,SAAiB,YAAY,KAAa;AAClE,WAAO,QAAQ,SAAS,YACpB,QAAQ,UAAU,GAAG,SAAS,IAAI,QAClC;AAAA,EACN;AACF;",
6
- "names": []
4
+ "sourcesContent": ["/**\n * Enhanced Context Rehydration System\n * Addresses compact summary limitations with rich context recovery\n *\n * Includes CompactionHandler for Claude Code Autocompaction\n * Preserves critical context across token limit boundaries\n */\n\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport { logger } from '../monitoring/logger.js';\nimport { FrameManager } from './index.js';\nimport type { Anchor, Event } from './index.js';\n\n// ============================================================================\n// Compaction Handler Types\n// ============================================================================\n\nexport interface CompactionMetrics {\n estimatedTokens: number;\n warningThreshold: number;\n criticalThreshold: number;\n lastCompactionAt?: number;\n anchorsPreserved: number;\n}\n\nexport interface ToolCallSummary {\n tool: string;\n timestamp: number;\n key_inputs: Record<string, any>;\n key_outputs: Record<string, any>;\n files_affected: string[];\n success: boolean;\n error?: string;\n}\n\nexport interface CriticalContextAnchor {\n anchor_id: string;\n type: 'COMPACTION_PRESERVE';\n priority: 10; // Highest priority\n content: {\n tool_calls: ToolCallSummary[];\n decisions: string[];\n file_operations: FileOperation[];\n error_resolutions: ErrorPattern[];\n };\n created_at: number;\n token_estimate: number;\n}\n\nexport interface FileOperation {\n type: 'read' | 'write' | 'edit' | 'delete' | 'create';\n path: string;\n timestamp: number;\n success: boolean;\n error?: string;\n}\n\nexport interface ErrorPattern {\n error: string;\n resolution: string;\n tool_sequence: string[];\n timestamp: number;\n}\n\n// ============================================================================\n// Compaction Handler Class\n// ============================================================================\n\nexport class CompactionHandler {\n private frameManager: FrameManager;\n private metrics: CompactionMetrics;\n private tokenAccumulator: number = 0;\n private preservedAnchors: Map<string, CriticalContextAnchor> = new Map();\n\n constructor(frameManager: FrameManager) {\n this.frameManager = frameManager;\n this.metrics = {\n estimatedTokens: 0,\n warningThreshold: 150000, // 150K tokens\n criticalThreshold: 170000, // 170K tokens\n anchorsPreserved: 0,\n };\n }\n\n /**\n * Track token usage from a message\n */\n trackTokens(content: string): void {\n // Rough estimation: 1 token \u2248 4 characters\n const estimatedTokens = Math.ceil(content.length / 4);\n this.tokenAccumulator += estimatedTokens;\n this.metrics.estimatedTokens += estimatedTokens;\n\n // Check thresholds\n if (this.isApproachingCompaction()) {\n this.preserveCriticalContext();\n }\n }\n\n /**\n * Check if approaching compaction threshold\n */\n isApproachingCompaction(): boolean {\n return this.metrics.estimatedTokens >= this.metrics.warningThreshold;\n }\n\n /**\n * Check if past critical threshold\n */\n isPastCriticalThreshold(): boolean {\n return this.metrics.estimatedTokens >= this.metrics.criticalThreshold;\n }\n\n /**\n * Detect if compaction likely occurred\n */\n detectCompactionEvent(content: string): boolean {\n const compactionIndicators = [\n 'earlier in this conversation',\n 'previously discussed',\n 'as mentioned before',\n 'summarized for brevity',\n '[conversation compressed]',\n '[context truncated]',\n ];\n\n const lowerContent = content.toLowerCase();\n return compactionIndicators.some((indicator) =>\n lowerContent.includes(indicator)\n );\n }\n\n /**\n * Preserve critical context before compaction\n */\n async preserveCriticalContext(): Promise<void> {\n try {\n const currentFrameId = this.frameManager.getCurrentFrameId();\n if (!currentFrameId) {\n logger.warn('No active frame to preserve context from');\n return;\n }\n\n // Get events from current frame\n const events = this.frameManager.getFrameEvents(currentFrameId);\n\n // Extract critical information\n const toolCalls = this.extractToolCalls(events);\n const fileOps = this.extractFileOperations(events);\n const decisions = this.extractDecisions(events);\n const errorPatterns = this.extractErrorPatterns(events);\n\n // Create preservation anchor\n const anchor: CriticalContextAnchor = {\n anchor_id: `compact_${Date.now()}`,\n type: 'COMPACTION_PRESERVE',\n priority: 10,\n content: {\n tool_calls: toolCalls,\n file_operations: fileOps,\n decisions: decisions,\n error_resolutions: errorPatterns,\n },\n created_at: Date.now(),\n token_estimate: this.metrics.estimatedTokens,\n };\n\n // Store in frame manager as high-priority anchor\n this.frameManager.addAnchor(\n 'CONSTRAINT' as any, // Using CONSTRAINT type for now\n JSON.stringify(anchor),\n 10,\n {\n compaction_preserve: true,\n token_count: this.metrics.estimatedTokens,\n },\n currentFrameId\n );\n\n // Store locally for quick access\n this.preservedAnchors.set(anchor.anchor_id, anchor);\n this.metrics.anchorsPreserved++;\n\n logger.info(\n `Preserved critical context at ${this.metrics.estimatedTokens} tokens`\n );\n } catch (error: unknown) {\n logger.error(\n 'Failed to preserve critical context:',\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Extract tool calls from events\n */\n private extractToolCalls(events: Event[]): ToolCallSummary[] {\n const toolCalls: ToolCallSummary[] = [];\n const toolEvents = events.filter((e) => e.event_type === 'tool_call');\n\n for (const event of toolEvents) {\n const resultEvent = events.find(\n (e) =>\n e.event_type === 'tool_result' &&\n e.seq > event.seq &&\n e.payload.tool_name === event.payload.tool_name\n );\n\n toolCalls.push({\n tool: event.payload.tool_name || 'unknown',\n timestamp: event.ts,\n key_inputs: this.extractKeyInputs(event.payload),\n key_outputs: resultEvent\n ? this.extractKeyOutputs(resultEvent.payload)\n : {},\n files_affected: this.extractAffectedFiles(\n event.payload,\n resultEvent?.payload\n ),\n success: resultEvent ? !resultEvent.payload.error : false,\n error: resultEvent?.payload.error,\n });\n }\n\n return toolCalls;\n }\n\n /**\n * Extract key inputs from tool call\n */\n private extractKeyInputs(payload: any): Record<string, any> {\n const keys = [\n 'file_path',\n 'command',\n 'query',\n 'path',\n 'pattern',\n 'content',\n ];\n const result: Record<string, any> = {};\n\n for (const key of keys) {\n if (payload.arguments?.[key]) {\n result[key] = payload.arguments[key];\n }\n }\n\n return result;\n }\n\n /**\n * Extract key outputs from tool result\n */\n private extractKeyOutputs(payload: any): Record<string, any> {\n return {\n success: !payload.error,\n error: payload.error,\n result_type: payload.result_type,\n files_created: payload.files_created,\n files_modified: payload.files_modified,\n };\n }\n\n /**\n * Extract affected files from tool events\n */\n private extractAffectedFiles(callPayload: any, resultPayload: any): string[] {\n const files = new Set<string>();\n\n // From tool call\n if (callPayload?.arguments?.file_path) {\n files.add(callPayload.arguments.file_path);\n }\n if (callPayload?.arguments?.path) {\n files.add(callPayload.arguments.path);\n }\n\n // From tool result\n if (resultPayload?.files_created) {\n resultPayload.files_created.forEach((f: string) => files.add(f));\n }\n if (resultPayload?.files_modified) {\n resultPayload.files_modified.forEach((f: string) => files.add(f));\n }\n\n return Array.from(files);\n }\n\n /**\n * Extract file operations from events\n */\n private extractFileOperations(events: Event[]): FileOperation[] {\n const fileOps: FileOperation[] = [];\n const fileTools = ['Read', 'Write', 'Edit', 'MultiEdit', 'Delete'];\n\n const toolEvents = events.filter(\n (e) =>\n e.event_type === 'tool_call' && fileTools.includes(e.payload.tool_name)\n );\n\n for (const event of toolEvents) {\n const operation = this.mapToolToOperation(event.payload.tool_name);\n const path =\n event.payload.arguments?.file_path ||\n event.payload.arguments?.path ||\n 'unknown';\n\n fileOps.push({\n type: operation,\n path: path,\n timestamp: event.ts,\n success: true, // Will be updated from result\n error: undefined,\n });\n }\n\n return fileOps;\n }\n\n /**\n * Map tool name to file operation type\n */\n private mapToolToOperation(toolName: string): FileOperation['type'] {\n const mapping: Record<string, FileOperation['type']> = {\n Read: 'read',\n Write: 'write',\n Edit: 'edit',\n MultiEdit: 'edit',\n Delete: 'delete',\n };\n\n return mapping[toolName] || 'read';\n }\n\n /**\n * Extract decisions from events\n */\n private extractDecisions(events: Event[]): string[] {\n const decisions: string[] = [];\n\n const decisionEvents = events.filter((e) => e.event_type === 'decision');\n for (const event of decisionEvents) {\n if (event.payload.text) {\n decisions.push(event.payload.text);\n }\n }\n\n return decisions;\n }\n\n /**\n * Extract error patterns and resolutions\n */\n private extractErrorPatterns(events: Event[]): ErrorPattern[] {\n const patterns: ErrorPattern[] = [];\n\n // Find tool results with errors\n const errorEvents = events.filter(\n (e) => e.event_type === 'tool_result' && e.payload.error\n );\n\n for (const errorEvent of errorEvents) {\n // Look for subsequent successful tool calls that might be resolutions\n const subsequentTools = events\n .filter((e) => e.event_type === 'tool_call' && e.seq > errorEvent.seq)\n .slice(0, 3); // Next 3 tools might be resolution attempts\n\n if (subsequentTools.length > 0) {\n patterns.push({\n error: errorEvent.payload.error,\n resolution: `Attempted resolution with ${subsequentTools.map((t) => t.payload.tool_name).join(', ')}`,\n tool_sequence: subsequentTools.map((t) => t.payload.tool_name),\n timestamp: errorEvent.ts,\n });\n }\n }\n\n return patterns;\n }\n\n /**\n * Restore context after compaction detected\n */\n async restoreContext(): Promise<void> {\n if (this.preservedAnchors.size === 0) {\n logger.warn('No preserved anchors to restore from');\n return;\n }\n\n // Get the most recent anchor\n const anchors = Array.from(this.preservedAnchors.values());\n anchors.sort((a, b) => b.created_at - a.created_at);\n const latestAnchor = anchors[0];\n\n // Create restoration frame\n const restorationFrame = this.frameManager.createFrame({\n type: 'review',\n name: 'Context Restoration After Compaction',\n inputs: { reason: 'autocompaction_detected' },\n });\n\n // Add restoration anchor\n this.frameManager.addAnchor(\n 'FACT',\n `Context restored from token position ${latestAnchor.token_estimate}`,\n 10,\n { restoration: true },\n restorationFrame\n );\n\n // Add tool sequence summary\n const toolSequence = latestAnchor.content.tool_calls\n .map((t) => t.tool)\n .join(' \u2192 ');\n this.frameManager.addAnchor(\n 'FACT',\n `Tool sequence: ${toolSequence}`,\n 9,\n {},\n restorationFrame\n );\n\n // Add file operations summary\n const files = new Set<string>();\n latestAnchor.content.file_operations.forEach((op) => files.add(op.path));\n if (files.size > 0) {\n this.frameManager.addAnchor(\n 'FACT',\n `Files touched: ${Array.from(files).join(', ')}`,\n 8,\n {},\n restorationFrame\n );\n }\n\n // Add decisions\n for (const decision of latestAnchor.content.decisions) {\n this.frameManager.addAnchor(\n 'DECISION',\n decision,\n 7,\n {},\n restorationFrame\n );\n }\n\n logger.info('Context restored after compaction detection');\n }\n\n /**\n * Get current metrics\n */\n getMetrics(): CompactionMetrics {\n return { ...this.metrics };\n }\n\n /**\n * Reset token counter (e.g., at session start)\n */\n resetTokenCount(): void {\n this.metrics.estimatedTokens = 0;\n this.tokenAccumulator = 0;\n this.metrics.lastCompactionAt = undefined;\n }\n}\n\n// ============================================================================\n// Enhanced Rehydration Types\n// ============================================================================\n\nexport interface FileSnapshot {\n path: string;\n content: string;\n size: number;\n lastModified: number;\n hash: string; // Quick change detection\n contextTags: string[]; // e.g., ['migration', 'pipedream', 'hubspot']\n}\n\nexport interface StackTrace {\n error_message: string;\n stack_frames: string[];\n file_path?: string;\n line_number?: number;\n function_name?: string;\n timestamp: number;\n context: string; // What was being done when error occurred\n resolution_attempted?: string[];\n resolution_status: 'pending' | 'resolved' | 'workaround' | 'blocked';\n}\n\nexport interface ConversationContext {\n timestamp: number;\n reasoning: string[];\n decisions_made: string[];\n next_steps: string[];\n user_preferences: Record<string, any>;\n pain_points: string[];\n stack_traces: StackTrace[];\n error_patterns: string[]; // Recurring error types\n}\n\nexport interface ProjectMapping {\n file_relationships: Record<string, string[]>; // file -> related files\n workflow_sequences: string[][]; // sequences of files in workflows\n key_directories: string[];\n entry_points: string[];\n configuration_files: string[];\n}\n\nexport interface RehydrationContext {\n session_id: string;\n compact_detected_at: number;\n pre_compact_state: {\n file_snapshots: FileSnapshot[];\n conversation_context: ConversationContext;\n project_mapping: ProjectMapping;\n active_workflows: string[];\n current_focus: string;\n };\n recovery_anchors: string[];\n}\n\nexport class EnhancedRehydrationManager {\n private frameManager: FrameManager;\n private compactionHandler: CompactionHandler;\n private snapshotThreshold = 10; // Take snapshot every N significant events\n private eventCount = 0;\n private rehydrationStorage = new Map<string, RehydrationContext>();\n\n constructor(\n frameManager: FrameManager,\n compactionHandler: CompactionHandler\n ) {\n this.frameManager = frameManager;\n this.compactionHandler = compactionHandler;\n this.setupCompactDetection();\n this.initializeStackTraceStorage();\n }\n\n /**\n * Initialize dedicated stack trace storage in database\n */\n private initializeStackTraceStorage(): void {\n try {\n const db = (this.frameManager as any).db; // Access the underlying database\n\n // Create stack_traces table for persistent storage\n db.exec(`\n CREATE TABLE IF NOT EXISTS stack_traces (\n trace_id TEXT PRIMARY KEY,\n frame_id TEXT,\n project_id TEXT NOT NULL,\n error_message TEXT NOT NULL,\n stack_frames TEXT NOT NULL,\n file_path TEXT,\n line_number INTEGER,\n function_name TEXT,\n context TEXT,\n resolution_attempted TEXT,\n resolution_status TEXT NOT NULL DEFAULT 'pending',\n error_type TEXT,\n error_severity TEXT DEFAULT 'medium',\n created_at INTEGER DEFAULT (unixepoch()),\n updated_at INTEGER DEFAULT (unixepoch()),\n FOREIGN KEY(frame_id) REFERENCES frames(frame_id)\n );\n\n CREATE INDEX IF NOT EXISTS idx_stack_traces_frame ON stack_traces(frame_id);\n CREATE INDEX IF NOT EXISTS idx_stack_traces_status ON stack_traces(resolution_status);\n CREATE INDEX IF NOT EXISTS idx_stack_traces_type ON stack_traces(error_type);\n CREATE INDEX IF NOT EXISTS idx_stack_traces_severity ON stack_traces(error_severity);\n CREATE INDEX IF NOT EXISTS idx_stack_traces_created ON stack_traces(created_at);\n `);\n\n logger.info('Stack trace storage initialized');\n } catch (error) {\n logger.error('Failed to initialize stack trace storage:', error);\n }\n }\n\n /**\n * Set up automatic compact detection and recovery\n */\n private setupCompactDetection(): void {\n // Monitor for compact indicators in new frames\n setInterval(() => this.checkForCompactionEvent(), 30000); // Check every 30s\n }\n\n /**\n * Enhanced file content snapshot with context\n */\n async captureFileSnapshot(\n filePath: string,\n contextTags: string[] = []\n ): Promise<FileSnapshot | null> {\n try {\n const stats = await fs.stat(filePath);\n const content = await fs.readFile(filePath, 'utf8');\n\n // Simple hash for change detection\n const hash = this.simpleHash(content);\n\n return {\n path: filePath,\n content: content,\n size: stats.size,\n lastModified: stats.mtimeMs,\n hash: hash,\n contextTags: contextTags,\n };\n } catch (error) {\n logger.warn(`Failed to capture snapshot for ${filePath}:`, error);\n return null;\n }\n }\n\n /**\n * Capture conversation reasoning and decisions including stack traces\n */\n captureConversationContext(\n reasoning: string[],\n decisions: string[],\n nextSteps: string[] = [],\n userPrefs: Record<string, any> = {},\n painPoints: string[] = [],\n stackTraces: StackTrace[] = [],\n errorPatterns: string[] = []\n ): ConversationContext {\n return {\n timestamp: Date.now(),\n reasoning: reasoning,\n decisions_made: decisions,\n next_steps: nextSteps,\n user_preferences: userPrefs,\n pain_points: painPoints,\n stack_traces: stackTraces,\n error_patterns: errorPatterns,\n };\n }\n\n /**\n * Capture stack trace from error with context and store in database\n */\n captureStackTrace(\n error: Error | string,\n context: string,\n filePath?: string,\n resolutionAttempts: string[] = [],\n frameId?: string\n ): StackTrace {\n const errorMessage = typeof error === 'string' ? error : error.message;\n const stackFrames =\n typeof error === 'string' ? [] : error.stack?.split('\\n') || [];\n\n // Extract file path and line number from stack if not provided\n let extractedFilePath = filePath;\n let lineNumber: number | undefined;\n let functionName: string | undefined;\n\n if (stackFrames.length > 0) {\n const firstFrame = stackFrames.find((frame) => frame.includes('at '));\n if (firstFrame) {\n const match = firstFrame.match(/at (.+?) \\((.+):(\\d+):(\\d+)\\)/);\n if (match) {\n functionName = match[1];\n extractedFilePath = extractedFilePath || match[2];\n lineNumber = parseInt(match[3]);\n }\n }\n }\n\n const stackTrace: StackTrace = {\n error_message: errorMessage,\n stack_frames: stackFrames,\n file_path: extractedFilePath,\n line_number: lineNumber,\n function_name: functionName,\n timestamp: Date.now(),\n context: context,\n resolution_attempted: resolutionAttempts,\n resolution_status: 'pending',\n };\n\n // Store in database\n this.storeStackTrace(stackTrace, frameId);\n\n return stackTrace;\n }\n\n /**\n * Store stack trace in database\n */\n private storeStackTrace(stackTrace: StackTrace, frameId?: string): string {\n try {\n const db = (this.frameManager as any).db;\n const traceId = this.generateTraceId();\n const currentFrameId = frameId || this.frameManager.getCurrentFrameId();\n\n // Determine error type and severity\n const errorType = this.extractErrorType(stackTrace.error_message);\n const severity = this.determineErrorSeverity(stackTrace);\n\n const stmt = db.prepare(`\n INSERT INTO stack_traces (\n trace_id, frame_id, project_id, error_message, stack_frames,\n file_path, line_number, function_name, context, resolution_attempted,\n resolution_status, error_type, error_severity\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n stmt.run(\n traceId,\n currentFrameId,\n (this.frameManager as any).projectId,\n stackTrace.error_message,\n JSON.stringify(stackTrace.stack_frames),\n stackTrace.file_path,\n stackTrace.line_number,\n stackTrace.function_name,\n stackTrace.context,\n JSON.stringify(stackTrace.resolution_attempted),\n stackTrace.resolution_status,\n errorType,\n severity\n );\n\n logger.info(`Stored stack trace ${traceId} for frame ${currentFrameId}`);\n return traceId;\n } catch (error) {\n logger.error('Failed to store stack trace:', error);\n return '';\n }\n }\n\n /**\n * Retrieve stack traces from database\n */\n public getStackTraces(frameId?: string, limit: number = 50): StackTrace[] {\n try {\n const db = (this.frameManager as any).db;\n const traces: StackTrace[] = [];\n\n let query: string;\n let params: any[];\n\n if (frameId) {\n query = `\n SELECT * FROM stack_traces \n WHERE frame_id = ? \n ORDER BY created_at DESC \n LIMIT ?\n `;\n params = [frameId, limit];\n } else {\n query = `\n SELECT * FROM stack_traces \n WHERE project_id = ? \n ORDER BY created_at DESC \n LIMIT ?\n `;\n params = [(this.frameManager as any).projectId, limit];\n }\n\n const rows = db.prepare(query).all(...params);\n\n for (const row of rows) {\n traces.push({\n error_message: row.error_message,\n stack_frames: JSON.parse(row.stack_frames || '[]'),\n file_path: row.file_path,\n line_number: row.line_number,\n function_name: row.function_name,\n timestamp: row.created_at * 1000, // Convert from unix to JS timestamp\n context: row.context,\n resolution_attempted: JSON.parse(row.resolution_attempted || '[]'),\n resolution_status: row.resolution_status,\n });\n }\n\n return traces;\n } catch (error) {\n logger.error('Failed to retrieve stack traces:', error);\n return [];\n }\n }\n\n /**\n * Update stack trace resolution status\n */\n public updateStackTraceStatus(\n traceId: string,\n status: StackTrace['resolution_status'],\n resolutionAttempts?: string[]\n ): boolean {\n try {\n const db = (this.frameManager as any).db;\n\n const stmt = db.prepare(`\n UPDATE stack_traces \n SET resolution_status = ?, resolution_attempted = ?, updated_at = unixepoch()\n WHERE trace_id = ?\n `);\n\n const result = stmt.run(\n status,\n resolutionAttempts ? JSON.stringify(resolutionAttempts) : undefined,\n traceId\n );\n\n return result.changes > 0;\n } catch (error) {\n logger.error('Failed to update stack trace status:', error);\n return false;\n }\n }\n\n /**\n * Helper methods for stack trace processing\n */\n private generateTraceId(): string {\n return `trace_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n private extractErrorType(errorMessage: string): string {\n const typeMatch = errorMessage.match(/^(\\w+Error?):/);\n return typeMatch ? typeMatch[1] : 'Unknown';\n }\n\n private determineErrorSeverity(stackTrace: StackTrace): string {\n const message = stackTrace.error_message.toLowerCase();\n\n if (\n message.includes('critical') ||\n message.includes('fatal') ||\n message.includes('cannot read properties')\n ) {\n return 'high';\n } else if (message.includes('warning') || message.includes('deprecated')) {\n return 'low';\n } else {\n return 'medium';\n }\n }\n\n /**\n * Auto-detect project structure and relationships\n */\n async analyzeProjectMapping(workingDir: string): Promise<ProjectMapping> {\n const mapping: ProjectMapping = {\n file_relationships: {},\n workflow_sequences: [],\n key_directories: [],\n entry_points: [],\n configuration_files: [],\n };\n\n try {\n // Find configuration files\n const configPatterns = [\n 'package.json',\n 'tsconfig.json',\n '.env',\n 'docker-compose.yml',\n '*.config.js',\n '*.config.ts',\n 'Dockerfile',\n 'README.md',\n ];\n\n // Analyze directory structure\n const files = await this.getDirectoryFiles(workingDir);\n\n for (const file of files) {\n const ext = path.extname(file);\n const basename = path.basename(file);\n\n // Identify configuration files\n if (\n configPatterns.some((pattern) =>\n pattern.includes('*')\n ? basename.includes(pattern.replace('*', ''))\n : basename === pattern\n )\n ) {\n mapping.configuration_files.push(file);\n }\n\n // Identify entry points\n if (\n basename === 'index.js' ||\n basename === 'index.ts' ||\n basename === 'main.js'\n ) {\n mapping.entry_points.push(file);\n }\n\n // Find related files based on naming patterns\n const filePrefix = basename.split('.')[0];\n const relatedFiles = files.filter(\n (f) => f !== file && path.basename(f).startsWith(filePrefix)\n );\n if (relatedFiles.length > 0) {\n mapping.file_relationships[file] = relatedFiles;\n }\n }\n\n // Identify key directories\n const dirs = files\n .map((f) => path.dirname(f))\n .filter((v, i, a) => a.indexOf(v) === i);\n mapping.key_directories = dirs.filter((dir) =>\n ['src', 'lib', 'components', 'pages', 'api', 'utils', 'types'].some(\n (key) => dir.includes(key)\n )\n );\n } catch (error) {\n logger.warn('Failed to analyze project mapping:', error);\n }\n\n return mapping;\n }\n\n /**\n * Create comprehensive rehydration context before compaction\n */\n async createRehydrationCheckpoint(): Promise<string> {\n const sessionId = this.frameManager.getSessionId() || 'unknown';\n const checkpointId = `${sessionId}_${Date.now()}`;\n\n try {\n // Get current working directory\n const workingDir = process.cwd();\n\n // Capture file snapshots for recently modified files\n const fileSnapshots: FileSnapshot[] = [];\n const recentFiles = await this.getRecentlyModifiedFiles(workingDir);\n\n for (const file of recentFiles.slice(0, 20)) {\n // Limit to 20 most recent\n const snapshot = await this.captureFileSnapshot(\n file,\n this.inferContextTags(file)\n );\n if (snapshot) {\n fileSnapshots.push(snapshot);\n }\n }\n\n // Capture project mapping\n const projectMapping = await this.analyzeProjectMapping(workingDir);\n\n // Extract conversation context from recent events\n const conversationContext = this.extractConversationContext();\n\n // Create rehydration context\n const rehydrationContext: RehydrationContext = {\n session_id: sessionId,\n compact_detected_at: Date.now(),\n pre_compact_state: {\n file_snapshots: fileSnapshots,\n conversation_context: conversationContext,\n project_mapping: projectMapping,\n active_workflows: this.detectActiveWorkflows(fileSnapshots),\n current_focus: this.inferCurrentFocus(\n fileSnapshots,\n conversationContext\n ),\n },\n recovery_anchors: this.createRecoveryAnchors(\n fileSnapshots,\n conversationContext\n ),\n };\n\n // Store for later retrieval\n this.rehydrationStorage.set(checkpointId, rehydrationContext);\n\n // Also persist to file system for cross-session recovery\n await this.persistRehydrationContext(checkpointId, rehydrationContext);\n\n logger.info(\n `Created rehydration checkpoint ${checkpointId} with ${fileSnapshots.length} file snapshots`\n );\n\n return checkpointId;\n } catch (error) {\n logger.error('Failed to create rehydration checkpoint:', error);\n throw error;\n }\n }\n\n /**\n * Inject rich context after compaction detection\n */\n async rehydrateContext(checkpointId?: string): Promise<boolean> {\n try {\n let context: RehydrationContext | undefined;\n\n if (checkpointId) {\n context = this.rehydrationStorage.get(checkpointId);\n if (!context) {\n context = await this.loadPersistedContext(checkpointId);\n }\n } else {\n // Find most recent context\n context = await this.findMostRecentContext();\n }\n\n if (!context) {\n logger.warn('No rehydration context available');\n return false;\n }\n\n await this.injectRichContext(context);\n return true;\n } catch (error) {\n logger.error('Failed to rehydrate context:', error);\n return false;\n }\n }\n\n /**\n * Inject rich context into current session\n */\n private async injectRichContext(context: RehydrationContext): Promise<void> {\n const frameId = this.frameManager.getCurrentFrameId();\n if (!frameId) {\n logger.warn('No active frame for context injection');\n return;\n }\n\n // Inject file context\n for (const snapshot of context.pre_compact_state.file_snapshots.slice(\n 0,\n 5\n )) {\n // Top 5 files\n this.frameManager.addAnchor(\n 'FACT',\n `File: ${snapshot.path} (${snapshot.contextTags.join(', ')})\\n` +\n `Last modified: ${new Date(snapshot.lastModified).toISOString()}\\n` +\n `Size: ${snapshot.size} bytes\\n` +\n `Content preview: ${this.getContentPreview(snapshot.content)}`,\n 9,\n {\n rehydration: true,\n file_path: snapshot.path,\n context_tags: snapshot.contextTags,\n },\n frameId\n );\n }\n\n // Inject conversation context\n const conv = context.pre_compact_state.conversation_context;\n if (conv.decisions_made.length > 0) {\n this.frameManager.addAnchor(\n 'DECISION',\n `Previous decisions: ${conv.decisions_made.join('; ')}`,\n 8,\n { rehydration: true },\n frameId\n );\n }\n\n if (conv.next_steps.length > 0) {\n this.frameManager.addAnchor(\n 'FACT',\n `Next steps identified: ${conv.next_steps.join('; ')}`,\n 7,\n { rehydration: true },\n frameId\n );\n }\n\n // Inject stack trace context\n if (conv.stack_traces.length > 0) {\n for (const trace of conv.stack_traces.slice(0, 3)) {\n // Top 3 most recent errors\n this.frameManager.addAnchor(\n 'ERROR',\n `Error context: ${trace.error_message}\\n` +\n `Context: ${trace.context}\\n` +\n `File: ${trace.file_path || 'unknown'}${trace.line_number ? `:${trace.line_number}` : ''}\\n` +\n `Function: ${trace.function_name || 'unknown'}\\n` +\n `Status: ${trace.resolution_status}\\n` +\n `Stack preview: ${trace.stack_frames.slice(0, 3).join('\\n')}`,\n 9,\n {\n rehydration: true,\n error_type: trace.error_message.split(':')[0],\n resolution_status: trace.resolution_status,\n file_path: trace.file_path,\n },\n frameId\n );\n }\n }\n\n // Inject error patterns\n if (conv.error_patterns.length > 0) {\n this.frameManager.addAnchor(\n 'PATTERN',\n `Recurring error patterns detected: ${conv.error_patterns.join(', ')}`,\n 7,\n { rehydration: true },\n frameId\n );\n }\n\n // Inject project mapping\n const mapping = context.pre_compact_state.project_mapping;\n if (mapping.entry_points.length > 0) {\n this.frameManager.addAnchor(\n 'FACT',\n `Project entry points: ${mapping.entry_points.join(', ')}`,\n 6,\n { rehydration: true },\n frameId\n );\n }\n\n // Inject current focus\n if (context.pre_compact_state.current_focus) {\n this.frameManager.addAnchor(\n 'CONSTRAINT',\n `Previous focus: ${context.pre_compact_state.current_focus}`,\n 8,\n { rehydration: true },\n frameId\n );\n }\n\n logger.info('Rich context injected successfully');\n }\n\n // Helper methods\n private async getDirectoryFiles(dir: string): Promise<string[]> {\n // Implementation to recursively get files\n return []; // Simplified for now\n }\n\n private async getRecentlyModifiedFiles(dir: string): Promise<string[]> {\n // Implementation to get recently modified files\n return []; // Simplified for now\n }\n\n private inferContextTags(filePath: string): string[] {\n const tags: string[] = [];\n const content = filePath.toLowerCase();\n\n if (content.includes('pipeline') || content.includes('migrate'))\n tags.push('migration');\n if (content.includes('hubspot')) tags.push('hubspot');\n if (content.includes('pipedream')) tags.push('pipedream');\n if (content.includes('test')) tags.push('test');\n if (content.includes('config')) tags.push('configuration');\n\n return tags;\n }\n\n private extractConversationContext(): ConversationContext {\n // Extract from recent frame events\n const recentErrors = this.extractRecentStackTraces();\n const errorPatterns = this.detectErrorPatterns(recentErrors);\n\n return {\n timestamp: Date.now(),\n reasoning: [],\n decisions_made: [],\n next_steps: [],\n user_preferences: {},\n pain_points: [],\n stack_traces: recentErrors,\n error_patterns: errorPatterns,\n };\n }\n\n /**\n * Extract recent stack traces from database and frame events\n */\n private extractRecentStackTraces(): StackTrace[] {\n try {\n // Get recent stack traces from database (most reliable source)\n const dbTraces = this.getStackTraces(undefined, 10);\n\n // Also check frame events for additional traces\n const eventTraces = this.extractStackTracesFromFrameEvents();\n\n // Combine and deduplicate\n const allTraces = [...dbTraces, ...eventTraces];\n\n // Remove duplicates based on error message and file path\n const uniqueTraces = allTraces.filter(\n (trace, index, array) =>\n array.findIndex(\n (t) =>\n t.error_message === trace.error_message &&\n t.file_path === trace.file_path\n ) === index\n );\n\n // Sort by timestamp (newest first) and return top 5\n return uniqueTraces.sort((a, b) => b.timestamp - a.timestamp).slice(0, 5);\n } catch (error) {\n logger.warn('Failed to extract stack traces:', error);\n return [];\n }\n }\n\n /**\n * Extract stack traces from frame events (fallback method)\n */\n private extractStackTracesFromFrameEvents(): StackTrace[] {\n const traces: StackTrace[] = [];\n\n try {\n // Get recent frames and look for error events\n const frames = this.frameManager.getActiveFramePath();\n\n for (const frame of frames.slice(-3)) {\n // Check last 3 frames\n const frameData = this.frameManager.getFrame(frame.frame_id);\n if (frameData?.events) {\n for (const event of frameData.events) {\n if (event.type === 'error' || event.type === 'exception') {\n const trace = this.parseStackTraceFromEvent(event);\n if (trace) {\n traces.push(trace);\n }\n }\n }\n }\n }\n } catch (error) {\n logger.warn('Failed to extract frame event traces:', error);\n }\n\n return traces;\n }\n\n /**\n * Parse stack trace from frame event\n */\n private parseStackTraceFromEvent(event: any): StackTrace | null {\n try {\n const data =\n typeof event.data === 'string' ? JSON.parse(event.data) : event.data;\n\n return {\n error_message: data.error || data.message || 'Unknown error',\n stack_frames: data.stack ? data.stack.split('\\n') : [],\n file_path: data.file || data.fileName,\n line_number: data.line || data.lineNumber,\n function_name: data.function || data.functionName,\n timestamp: event.timestamp || Date.now(),\n context: data.context || 'Error occurred during frame processing',\n resolution_attempted: data.resolutionAttempts || [],\n resolution_status: data.resolved ? 'resolved' : 'pending',\n };\n } catch (error) {\n return null;\n }\n }\n\n /**\n * Detect recurring error patterns\n */\n private detectErrorPatterns(traces: StackTrace[]): string[] {\n const patterns = new Map<string, number>();\n\n for (const trace of traces) {\n // Extract error type from message\n const errorType = trace.error_message.split(':')[0].trim();\n patterns.set(errorType, (patterns.get(errorType) || 0) + 1);\n }\n\n // Return patterns that occur more than once\n return Array.from(patterns.entries())\n .filter(([, count]) => count > 1)\n .map(([pattern]) => pattern);\n }\n\n private detectActiveWorkflows(snapshots: FileSnapshot[]): string[] {\n const workflows: string[] = [];\n\n for (const snapshot of snapshots) {\n if (snapshot.contextTags.includes('migration')) {\n workflows.push('data_migration');\n }\n if (snapshot.path.includes('test')) {\n workflows.push('testing');\n }\n }\n\n return [...new Set(workflows)];\n }\n\n private inferCurrentFocus(\n snapshots: FileSnapshot[],\n context: ConversationContext\n ): string {\n // Analyze recent file activity and conversation to infer focus\n if (snapshots.some((s) => s.contextTags.includes('migration'))) {\n return 'Data migration and transformation';\n }\n if (snapshots.some((s) => s.path.includes('test'))) {\n return 'Testing and validation';\n }\n return 'Development';\n }\n\n private createRecoveryAnchors(\n snapshots: FileSnapshot[],\n context: ConversationContext\n ): string[] {\n const anchors: string[] = [];\n\n // Create anchor points for each significant file\n for (const snapshot of snapshots.slice(0, 3)) {\n anchors.push(\n `File context: ${snapshot.path} with ${snapshot.contextTags.join(', ')}`\n );\n }\n\n return anchors;\n }\n\n private async persistRehydrationContext(\n id: string,\n context: RehydrationContext\n ): Promise<void> {\n // Implementation to persist context to filesystem\n const contextDir = path.join(process.cwd(), '.stackmemory', 'rehydration');\n await fs.mkdir(contextDir, { recursive: true });\n await fs.writeFile(\n path.join(contextDir, `${id}.json`),\n JSON.stringify(context, null, 2)\n );\n }\n\n private async loadPersistedContext(\n id: string\n ): Promise<RehydrationContext | undefined> {\n try {\n const contextPath = path.join(\n process.cwd(),\n '.stackmemory',\n 'rehydration',\n `${id}.json`\n );\n const content = await fs.readFile(contextPath, 'utf8');\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n }\n\n private async findMostRecentContext(): Promise<\n RehydrationContext | undefined\n > {\n // Find most recent persisted context\n return undefined; // Simplified for now\n }\n\n private checkForCompactionEvent(): void {\n // Check if compaction occurred and trigger rehydration\n if (this.compactionHandler.detectCompactionEvent('')) {\n this.rehydrateContext();\n }\n }\n\n private simpleHash(content: string): string {\n let hash = 0;\n for (let i = 0; i < content.length; i++) {\n const char = content.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash.toString(16);\n }\n\n private getContentPreview(content: string, maxLength = 200): string {\n return content.length > maxLength\n ? content.substring(0, maxLength) + '...'\n : content;\n }\n}\n"],
5
+ "mappings": ";;;;AAQA,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAA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,IACjC;AAAA,EACF;AAAA,EAEA,MAAc,qBACZ,IACyC;AACzC,QAAI;AACF,YAAM,cAAc,KAAK;AAAA,QACvB,QAAQ,IAAI;AAAA,QACZ;AAAA,QACA;AAAA,QACA,GAAG,EAAE;AAAA,MACP;AACA,YAAM,UAAU,MAAM,GAAG,SAAS,aAAa,MAAM;AACrD,aAAO,KAAK,MAAM,OAAO;AAAA,IAC3B,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAAA,EAEA,MAAc,wBAEZ;AAEA,WAAO;AAAA,EACT;AAAA,EAEQ,0BAAgC;AAEtC,QAAI,KAAK,kBAAkB,sBAAsB,EAAE,GAAG;AACpD,WAAK,iBAAiB;AAAA,IACxB;AAAA,EACF;AAAA,EAEQ,WAAW,SAAyB;AAC1C,QAAI,OAAO;AACX,aAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,YAAM,OAAO,QAAQ,WAAW,CAAC;AACjC,cAAQ,QAAQ,KAAK,OAAO;AAC5B,aAAO,OAAO;AAAA,IAChB;AACA,WAAO,KAAK,SAAS,EAAE;AAAA,EACzB;AAAA,EAEQ,kBAAkB,SAAiB,YAAY,KAAa;AAClE,WAAO,QAAQ,SAAS,YACpB,QAAQ,UAAU,GAAG,SAAS,IAAI,QAClC;AAAA,EACN;AACF;",
6
+ "names": ["path"]
7
7
  }
@@ -6,6 +6,7 @@ import { v4 as uuidv4 } from "uuid";
6
6
  import * as fs from "fs/promises";
7
7
  import * as path from "path";
8
8
  import { sessionManager } from "../session/session-manager.js";
9
+ import { logger } from "../monitoring/logger.js";
9
10
  class SharedContextLayer {
10
11
  static instance;
11
12
  contextDir;
@@ -385,8 +386,236 @@ class SharedContextLayer {
385
386
  }
386
387
  }
387
388
  const sharedContextLayer = SharedContextLayer.getInstance();
389
+ class ContextBridge {
390
+ static instance;
391
+ frameManager = null;
392
+ syncTimer = null;
393
+ lastSyncTime = 0;
394
+ options = {
395
+ autoSync: true,
396
+ syncInterval: 6e4,
397
+ // 1 minute
398
+ minFrameScore: 0.5,
399
+ // Include frames with score above 0.5
400
+ importantTags: ["decision", "error", "milestone", "learning"]
401
+ };
402
+ constructor() {
403
+ }
404
+ static getInstance() {
405
+ if (!ContextBridge.instance) {
406
+ ContextBridge.instance = new ContextBridge();
407
+ }
408
+ return ContextBridge.instance;
409
+ }
410
+ /**
411
+ * Initialize the bridge with a frame manager
412
+ */
413
+ async initialize(frameManager, options) {
414
+ this.frameManager = frameManager;
415
+ this.options = { ...this.options, ...options };
416
+ await this.loadSharedContext();
417
+ if (this.options.autoSync) {
418
+ this.startAutoSync();
419
+ }
420
+ logger.info("Context bridge initialized", {
421
+ autoSync: this.options.autoSync,
422
+ syncInterval: this.options.syncInterval
423
+ });
424
+ }
425
+ /**
426
+ * Load relevant shared context into current session
427
+ */
428
+ async loadSharedContext() {
429
+ try {
430
+ const session = sessionManager.getCurrentSession();
431
+ if (!session) return;
432
+ const discovery = await sharedContextLayer.autoDiscoverContext();
433
+ if (!discovery.hasSharedContext) {
434
+ logger.info("No shared context available to load");
435
+ return;
436
+ }
437
+ if (discovery.recentPatterns.length > 0) {
438
+ logger.info("Loaded recent patterns from shared context", {
439
+ patternCount: discovery.recentPatterns.length
440
+ });
441
+ }
442
+ if (discovery.lastDecisions.length > 0) {
443
+ logger.info("Loaded recent decisions from shared context", {
444
+ decisionCount: discovery.lastDecisions.length
445
+ });
446
+ }
447
+ if (discovery.suggestedFrames.length > 0) {
448
+ const metadata = {
449
+ suggestedFrames: discovery.suggestedFrames,
450
+ loadedAt: Date.now()
451
+ };
452
+ if (this.frameManager) {
453
+ await this.frameManager.addContext(
454
+ "shared-context-suggestions",
455
+ metadata
456
+ );
457
+ }
458
+ logger.info("Loaded suggested frames from shared context", {
459
+ frameCount: discovery.suggestedFrames.length
460
+ });
461
+ }
462
+ } catch (error) {
463
+ logger.error("Failed to load shared context", error);
464
+ }
465
+ }
466
+ /**
467
+ * Sync current session's important frames to shared context
468
+ */
469
+ async syncToSharedContext() {
470
+ try {
471
+ if (!this.frameManager) return;
472
+ const session = sessionManager.getCurrentSession();
473
+ if (!session) return;
474
+ const activeFrames = this.frameManager.getActiveFramePath().filter(Boolean);
475
+ const recentFrames = await this.frameManager.getRecentFrames(100);
476
+ const allFrames = [...activeFrames, ...recentFrames].filter(Boolean);
477
+ const importantFrames = this.filterImportantFrames(allFrames);
478
+ if (importantFrames.length === 0) {
479
+ logger.debug("No important frames to sync");
480
+ return;
481
+ }
482
+ await sharedContextLayer.addToSharedContext(importantFrames, {
483
+ minScore: this.options.minFrameScore,
484
+ tags: this.options.importantTags
485
+ });
486
+ this.lastSyncTime = Date.now();
487
+ logger.info("Synced frames to shared context", {
488
+ frameCount: importantFrames.length,
489
+ sessionId: session.sessionId
490
+ });
491
+ } catch (error) {
492
+ logger.error("Failed to sync to shared context", error);
493
+ }
494
+ }
495
+ /**
496
+ * Query shared context for relevant frames
497
+ */
498
+ async querySharedFrames(query) {
499
+ try {
500
+ const results = await sharedContextLayer.querySharedContext({
501
+ ...query,
502
+ minScore: this.options.minFrameScore
503
+ });
504
+ logger.info("Queried shared context", {
505
+ query,
506
+ resultCount: results.length
507
+ });
508
+ return results;
509
+ } catch (error) {
510
+ logger.error("Failed to query shared context", error);
511
+ return [];
512
+ }
513
+ }
514
+ /**
515
+ * Add a decision to shared context
516
+ */
517
+ async addDecision(decision, reasoning) {
518
+ try {
519
+ await sharedContextLayer.addDecision({
520
+ decision,
521
+ reasoning,
522
+ outcome: "pending"
523
+ });
524
+ logger.info("Added decision to shared context", { decision });
525
+ } catch (error) {
526
+ logger.error("Failed to add decision", error);
527
+ }
528
+ }
529
+ /**
530
+ * Start automatic synchronization
531
+ */
532
+ startAutoSync() {
533
+ if (this.syncTimer) {
534
+ clearInterval(this.syncTimer);
535
+ }
536
+ this.syncTimer = setInterval(() => {
537
+ this.syncToSharedContext().catch((error) => {
538
+ logger.error("Auto-sync failed", error);
539
+ });
540
+ }, this.options.syncInterval);
541
+ this.setupEventListeners();
542
+ }
543
+ /**
544
+ * Stop automatic synchronization
545
+ */
546
+ stopAutoSync() {
547
+ if (this.syncTimer) {
548
+ clearInterval(this.syncTimer);
549
+ this.syncTimer = null;
550
+ }
551
+ }
552
+ /**
553
+ * Filter frames that are important enough to share
554
+ */
555
+ filterImportantFrames(frames) {
556
+ return frames.filter((frame) => {
557
+ const hasImportantTag = this.options.importantTags.some(
558
+ (tag) => frame.metadata?.tags?.includes(tag)
559
+ );
560
+ const isImportantType = [
561
+ "task",
562
+ "milestone",
563
+ "error",
564
+ "resolution",
565
+ "decision"
566
+ ].includes(frame.type);
567
+ const markedImportant = frame.metadata?.importance === "high";
568
+ return hasImportantTag || isImportantType || markedImportant;
569
+ });
570
+ }
571
+ /**
572
+ * Setup event listeners for automatic syncing
573
+ */
574
+ setupEventListeners() {
575
+ if (!this.frameManager) return;
576
+ const originalClose = this.frameManager.closeFrame.bind(this.frameManager);
577
+ this.frameManager.closeFrame = async (frameId, metadata) => {
578
+ const result = await originalClose(frameId, metadata);
579
+ const frame = await this.frameManager.getFrame(frameId);
580
+ if (frame && this.filterImportantFrames([frame]).length > 0) {
581
+ await this.syncToSharedContext();
582
+ }
583
+ return result;
584
+ };
585
+ const originalMilestone = this.frameManager.createFrame.bind(
586
+ this.frameManager
587
+ );
588
+ this.frameManager.createFrame = async (params) => {
589
+ const result = await originalMilestone(params);
590
+ if (params.type === "milestone") {
591
+ await this.syncToSharedContext();
592
+ }
593
+ return result;
594
+ };
595
+ }
596
+ /**
597
+ * Get sync statistics
598
+ */
599
+ getSyncStats() {
600
+ return {
601
+ lastSyncTime: this.lastSyncTime,
602
+ autoSyncEnabled: this.options.autoSync,
603
+ syncInterval: this.options.syncInterval
604
+ };
605
+ }
606
+ /**
607
+ * Manual trigger for immediate sync
608
+ */
609
+ async forceSyncNow() {
610
+ logger.info("Force sync triggered");
611
+ await this.syncToSharedContext();
612
+ }
613
+ }
614
+ const contextBridge = ContextBridge.getInstance();
388
615
  export {
616
+ ContextBridge,
389
617
  SharedContextLayer,
618
+ contextBridge,
390
619
  sharedContextLayer
391
620
  };
392
621
  //# sourceMappingURL=shared-context-layer.js.map