@stackmemoryai/stackmemory 0.3.6 → 0.3.7
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.
- package/dist/agents/verifiers/base-verifier.js.map +2 -2
- package/dist/agents/verifiers/formatter-verifier.js.map +2 -2
- package/dist/agents/verifiers/llm-judge.js.map +2 -2
- package/dist/cli/claude-sm.js +24 -13
- package/dist/cli/claude-sm.js.map +2 -2
- package/dist/cli/codex-sm.js +24 -13
- package/dist/cli/codex-sm.js.map +2 -2
- package/dist/cli/commands/agent.js.map +2 -2
- package/dist/cli/commands/chromadb.js +217 -32
- package/dist/cli/commands/chromadb.js.map +2 -2
- package/dist/cli/commands/clear.js +12 -1
- package/dist/cli/commands/clear.js.map +2 -2
- package/dist/cli/commands/context.js +13 -2
- package/dist/cli/commands/context.js.map +2 -2
- package/dist/cli/commands/dashboard.js.map +2 -2
- package/dist/cli/commands/gc.js +202 -0
- package/dist/cli/commands/gc.js.map +7 -0
- package/dist/cli/commands/handoff.js +12 -1
- package/dist/cli/commands/handoff.js.map +2 -2
- package/dist/cli/commands/infinite-storage.js +32 -21
- package/dist/cli/commands/infinite-storage.js.map +2 -2
- package/dist/cli/commands/linear-create.js +13 -2
- package/dist/cli/commands/linear-create.js.map +2 -2
- package/dist/cli/commands/linear-list.js +12 -1
- package/dist/cli/commands/linear-list.js.map +2 -2
- package/dist/cli/commands/linear-migrate.js +12 -1
- package/dist/cli/commands/linear-migrate.js.map +2 -2
- package/dist/cli/commands/linear-test.js +12 -1
- package/dist/cli/commands/linear-test.js.map +2 -2
- package/dist/cli/commands/linear-unified.js +262 -0
- package/dist/cli/commands/linear-unified.js.map +7 -0
- package/dist/cli/commands/linear.js +17 -6
- package/dist/cli/commands/linear.js.map +2 -2
- package/dist/cli/commands/monitor.js.map +2 -2
- package/dist/cli/commands/onboard.js.map +2 -2
- package/dist/cli/commands/quality.js.map +2 -2
- package/dist/cli/commands/search.js.map +2 -2
- package/dist/cli/commands/session.js.map +2 -2
- package/dist/cli/commands/skills.js +12 -1
- package/dist/cli/commands/skills.js.map +2 -2
- package/dist/cli/commands/storage.js +18 -7
- package/dist/cli/commands/storage.js.map +2 -2
- package/dist/cli/commands/tasks.js.map +2 -2
- package/dist/cli/commands/tui.js +13 -2
- package/dist/cli/commands/tui.js.map +2 -2
- package/dist/cli/commands/webhook.js +14 -3
- package/dist/cli/commands/webhook.js.map +2 -2
- package/dist/cli/commands/workflow.js +14 -3
- package/dist/cli/commands/workflow.js.map +2 -2
- package/dist/cli/commands/worktree.js.map +2 -2
- package/dist/cli/index.js +18 -5
- package/dist/cli/index.js.map +2 -2
- package/dist/core/config/config-manager.js.map +2 -2
- package/dist/core/context/auto-context.js.map +2 -2
- package/dist/core/context/compaction-handler.js.map +2 -2
- package/dist/core/context/context-bridge.js.map +2 -2
- package/dist/core/context/dual-stack-manager.js.map +2 -2
- package/dist/core/context/frame-database.js.map +2 -2
- package/dist/core/context/frame-digest.js.map +2 -2
- package/dist/core/context/frame-handoff-manager.js.map +2 -2
- package/dist/core/context/frame-manager.js +12 -1
- package/dist/core/context/frame-manager.js.map +2 -2
- package/dist/core/context/frame-stack.js.map +2 -2
- package/dist/core/context/incremental-gc.js +279 -0
- package/dist/core/context/incremental-gc.js.map +7 -0
- package/dist/core/context/permission-manager.js +12 -1
- package/dist/core/context/permission-manager.js.map +2 -2
- package/dist/core/context/refactored-frame-manager.js.map +2 -2
- package/dist/core/context/shared-context-layer.js +12 -1
- package/dist/core/context/shared-context-layer.js.map +2 -2
- package/dist/core/context/stack-merge-resolver.js.map +2 -2
- package/dist/core/context/validation.js.map +2 -2
- package/dist/core/database/batch-operations.js.map +2 -2
- package/dist/core/database/connection-pool.js.map +2 -2
- package/dist/core/database/migration-manager.js.map +2 -2
- package/dist/core/database/paradedb-adapter.js.map +2 -2
- package/dist/core/database/query-cache.js.map +2 -2
- package/dist/core/database/query-router.js.map +2 -2
- package/dist/core/database/sqlite-adapter.js.map +2 -2
- package/dist/core/digest/enhanced-hybrid-digest.js.map +2 -2
- package/dist/core/errors/recovery.js.map +2 -2
- package/dist/core/merge/resolution-engine.js.map +2 -2
- package/dist/core/monitoring/error-handler.js.map +2 -2
- package/dist/core/monitoring/logger.js +14 -3
- package/dist/core/monitoring/logger.js.map +2 -2
- package/dist/core/monitoring/metrics.js +13 -2
- package/dist/core/monitoring/metrics.js.map +2 -2
- package/dist/core/monitoring/progress-tracker.js +12 -1
- package/dist/core/monitoring/progress-tracker.js.map +2 -2
- package/dist/core/monitoring/session-monitor.js.map +2 -2
- package/dist/core/performance/context-cache.js.map +2 -2
- package/dist/core/performance/lazy-context-loader.js.map +2 -2
- package/dist/core/performance/monitor.js.map +2 -2
- package/dist/core/performance/optimized-frame-context.js.map +2 -2
- package/dist/core/performance/performance-benchmark.js.map +2 -2
- package/dist/core/performance/performance-profiler.js +12 -1
- package/dist/core/performance/performance-profiler.js.map +2 -2
- package/dist/core/performance/streaming-jsonl-parser.js.map +2 -2
- package/dist/core/persistence/postgres-adapter.js.map +2 -2
- package/dist/core/projects/project-manager.js.map +2 -2
- package/dist/core/retrieval/context-retriever.js.map +2 -2
- package/dist/core/retrieval/graph-retrieval.js.map +2 -2
- package/dist/core/retrieval/llm-context-retrieval.js.map +2 -2
- package/dist/core/retrieval/retrieval-benchmarks.js.map +2 -2
- package/dist/core/retrieval/summary-generator.js.map +2 -2
- package/dist/core/session/clear-survival.js.map +2 -2
- package/dist/core/session/handoff-generator.js.map +2 -2
- package/dist/core/session/session-manager.js +16 -5
- package/dist/core/session/session-manager.js.map +2 -2
- package/dist/core/skills/skill-storage.js +13 -2
- package/dist/core/skills/skill-storage.js.map +2 -2
- package/dist/core/storage/chromadb-adapter.js.map +2 -2
- package/dist/core/storage/chromadb-simple.js.map +2 -2
- package/dist/core/storage/infinite-storage.js.map +2 -2
- package/dist/core/storage/railway-optimized-storage.js +19 -8
- package/dist/core/storage/railway-optimized-storage.js.map +2 -2
- package/dist/core/storage/remote-storage.js +12 -1
- package/dist/core/storage/remote-storage.js.map +2 -2
- package/dist/core/trace/cli-trace-wrapper.js +16 -5
- package/dist/core/trace/cli-trace-wrapper.js.map +2 -2
- package/dist/core/trace/db-trace-wrapper.js.map +2 -2
- package/dist/core/trace/debug-trace.js +21 -10
- package/dist/core/trace/debug-trace.js.map +2 -2
- package/dist/core/trace/index.js +46 -35
- package/dist/core/trace/index.js.map +2 -2
- package/dist/core/trace/trace-demo.js +12 -1
- package/dist/core/trace/trace-demo.js.map +2 -2
- package/dist/core/trace/trace-detector.js.map +2 -2
- package/dist/core/trace/trace-store.js.map +2 -2
- package/dist/core/utils/update-checker.js.map +2 -2
- package/dist/core/worktree/worktree-manager.js.map +2 -2
- package/dist/features/analytics/api/analytics-api.js.map +2 -2
- package/dist/features/analytics/core/analytics-service.js +12 -1
- package/dist/features/analytics/core/analytics-service.js.map +2 -2
- package/dist/features/analytics/queries/metrics-queries.js.map +2 -2
- package/dist/features/tasks/pebbles-task-store.js.map +2 -2
- package/dist/features/tui/components/analytics-panel.js.map +2 -2
- package/dist/features/tui/components/pr-tracker.js.map +2 -2
- package/dist/features/tui/components/session-monitor.js.map +2 -2
- package/dist/features/tui/components/subagent-fleet.js.map +2 -2
- package/dist/features/tui/components/task-board.js +650 -2
- package/dist/features/tui/components/task-board.js.map +2 -2
- package/dist/features/tui/index.js +16 -5
- package/dist/features/tui/index.js.map +2 -2
- package/dist/features/tui/services/data-service.js +25 -14
- package/dist/features/tui/services/data-service.js.map +2 -2
- package/dist/features/tui/services/linear-task-reader.js.map +2 -2
- package/dist/features/tui/services/websocket-client.js +13 -2
- package/dist/features/tui/services/websocket-client.js.map +2 -2
- package/dist/features/tui/terminal-compat.js +27 -16
- package/dist/features/tui/terminal-compat.js.map +2 -2
- package/dist/features/web/client/stores/task-store.js.map +2 -2
- package/dist/features/web/server/index.js +13 -2
- package/dist/features/web/server/index.js.map +2 -2
- package/dist/integrations/claude-code/enhanced-pre-clear-hooks.js.map +2 -2
- package/dist/integrations/claude-code/lifecycle-hooks.js.map +2 -2
- package/dist/integrations/claude-code/post-task-hooks.js.map +2 -2
- package/dist/integrations/linear/auth.js +17 -6
- package/dist/integrations/linear/auth.js.map +2 -2
- package/dist/integrations/linear/auto-sync.js.map +2 -2
- package/dist/integrations/linear/client.js.map +2 -2
- package/dist/integrations/linear/config.js.map +2 -2
- package/dist/integrations/linear/migration.js.map +2 -2
- package/dist/integrations/linear/oauth-server.js +13 -2
- package/dist/integrations/linear/oauth-server.js.map +2 -2
- package/dist/integrations/linear/rest-client.js.map +2 -2
- package/dist/integrations/linear/sync-enhanced.js +202 -0
- package/dist/integrations/linear/sync-enhanced.js.map +7 -0
- package/dist/integrations/linear/sync-manager.js.map +2 -2
- package/dist/integrations/linear/sync-service.js +12 -1
- package/dist/integrations/linear/sync-service.js.map +2 -2
- package/dist/integrations/linear/sync.js +34 -3
- package/dist/integrations/linear/sync.js.map +2 -2
- package/dist/integrations/linear/unified-sync.js +560 -0
- package/dist/integrations/linear/unified-sync.js.map +7 -0
- package/dist/integrations/linear/webhook-handler.js +12 -1
- package/dist/integrations/linear/webhook-handler.js.map +2 -2
- package/dist/integrations/linear/webhook-server.js +14 -3
- package/dist/integrations/linear/webhook-server.js.map +2 -2
- package/dist/integrations/linear/webhook.js +12 -1
- package/dist/integrations/linear/webhook.js.map +2 -2
- package/dist/integrations/mcp/handlers/context-handlers.js.map +2 -2
- package/dist/integrations/mcp/handlers/linear-handlers.js.map +2 -2
- package/dist/integrations/mcp/handlers/skill-handlers.js +13 -2
- package/dist/integrations/mcp/handlers/skill-handlers.js.map +2 -2
- package/dist/integrations/mcp/handlers/task-handlers.js.map +2 -2
- package/dist/integrations/mcp/handlers/trace-handlers.js.map +2 -2
- package/dist/integrations/mcp/middleware/tool-scoring.js.map +2 -2
- package/dist/integrations/mcp/refactored-server.js +15 -4
- package/dist/integrations/mcp/refactored-server.js.map +2 -2
- package/dist/integrations/mcp/server.js +12 -1
- package/dist/integrations/mcp/server.js.map +2 -2
- package/dist/integrations/mcp/tool-definitions.js.map +2 -2
- package/dist/integrations/pg-aiguide/embedding-provider.js +13 -2
- package/dist/integrations/pg-aiguide/embedding-provider.js.map +2 -2
- package/dist/integrations/pg-aiguide/semantic-search.js.map +2 -2
- package/dist/mcp/stackmemory-mcp-server.js +12 -1
- package/dist/mcp/stackmemory-mcp-server.js.map +2 -2
- package/dist/middleware/exponential-rate-limiter.js.map +2 -2
- package/dist/servers/production/auth-middleware.js +13 -2
- package/dist/servers/production/auth-middleware.js.map +2 -2
- package/dist/servers/railway/index.js +22 -11
- package/dist/servers/railway/index.js.map +2 -2
- package/dist/services/config-service.js.map +2 -2
- package/dist/services/context-service.js.map +2 -2
- package/dist/skills/claude-skills.js +105 -2
- package/dist/skills/claude-skills.js.map +2 -2
- package/dist/skills/dashboard-launcher.js.map +2 -2
- package/dist/skills/repo-ingestion-skill.js +561 -0
- package/dist/skills/repo-ingestion-skill.js.map +7 -0
- package/dist/utils/logger.js +12 -1
- package/dist/utils/logger.js.map +2 -2
- package/package.json +5 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/core/merge/resolution-engine.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Resolution Engine\n * Implements multiple strategies for resolving merge conflicts\n */\n\nimport { v4 as uuidv4 } from 'uuid';\nimport {\n MergeConflict,\n ConflictResolution,\n ResolutionStrategy,\n TeamVote,\n FrameStack,\n MergeResult,\n NotificationResult,\n} from './types.js';\nimport { Frame } from '../context/frame-manager.js';\nimport { ConflictDetector } from './conflict-detector.js';\nimport { StackDiffVisualizer } from './stack-diff.js';\nimport { logger } from '../monitoring/logger.js';\n\nexport interface ResolutionContext {\n userId: string;\n userRole: 'junior' | 'mid' | 'senior' | 'lead';\n teamVotes?: TeamVote[];\n aiConfidence?: number;\n timeConstraint?: number; // milliseconds\n}\n\nexport class ResolutionEngine {\n private conflictDetector: ConflictDetector;\n private diffVisualizer: StackDiffVisualizer;\n private resolutionHistory: Map<string, ConflictResolution> = new Map();\n\n constructor() {\n this.conflictDetector = new ConflictDetector();\n this.diffVisualizer = new StackDiffVisualizer();\n }\n\n /**\n * Resolve conflicts using the specified strategy\n */\n async resolveConflicts(\n stack1: FrameStack,\n stack2: FrameStack,\n strategy: ResolutionStrategy['type'],\n context: ResolutionContext\n ): Promise<MergeResult> {\n const conflicts = this.conflictDetector.detectConflicts(stack1, stack2);\n\n logger.info(\n `Resolving ${conflicts.length} conflicts using ${strategy} strategy`,\n {\n userId: context.userId,\n userRole: context.userRole,\n }\n );\n\n let resolution: ConflictResolution;\n\n switch (strategy) {\n case 'keep_both':\n resolution = await this.keepBothStrategy(\n conflicts,\n stack1,\n stack2,\n context\n );\n break;\n\n case 'team_vote':\n resolution = await this.teamVoteStrategy(\n conflicts,\n stack1,\n stack2,\n context\n );\n break;\n\n case 'senior_override':\n resolution = await this.seniorOverrideStrategy(\n conflicts,\n stack1,\n stack2,\n context\n );\n break;\n\n case 'ai_suggest':\n resolution = await this.aiSuggestStrategy(\n conflicts,\n stack1,\n stack2,\n context\n );\n break;\n\n case 'hybrid':\n resolution = await this.hybridStrategy(\n conflicts,\n stack1,\n stack2,\n context\n );\n break;\n\n default:\n throw new Error(`Unknown resolution strategy: ${strategy}`);\n }\n\n // Execute the merge based on resolution\n const mergeResult = await this.executeMerge(\n stack1,\n stack2,\n conflicts,\n resolution\n );\n\n // Store resolution in history\n this.storeResolution(mergeResult.mergedFrameId || '', resolution);\n\n return mergeResult;\n }\n\n /**\n * Strategy: Keep Both Solutions\n * Creates a merged frame that includes both approaches\n */\n private async keepBothStrategy(\n conflicts: MergeConflict[],\n stack1: FrameStack,\n stack2: FrameStack,\n context: ResolutionContext\n ): Promise<ConflictResolution> {\n logger.info('Applying keep_both strategy');\n\n const strategy: ResolutionStrategy = {\n type: 'keep_both',\n confidence: 0.8,\n reasoning:\n 'Preserving both solutions to maintain all work and allow future evaluation',\n };\n\n // Mark all conflicts as resolved by keeping both\n for (const conflict of conflicts) {\n conflict.resolution = {\n strategy,\n resolvedBy: context.userId,\n resolvedAt: Date.now(),\n notes: 'Both solutions preserved in merged frame',\n };\n }\n\n return {\n strategy,\n resolvedBy: context.userId,\n resolvedAt: Date.now(),\n notes: `Kept all ${stack1.frames.length + stack2.frames.length} frames from both stacks`,\n };\n }\n\n /**\n * Strategy: Team Vote\n * Uses democratic voting to choose between options\n */\n private async teamVoteStrategy(\n conflicts: MergeConflict[],\n stack1: FrameStack,\n stack2: FrameStack,\n context: ResolutionContext\n ): Promise<ConflictResolution> {\n logger.info('Applying team_vote strategy');\n\n if (!context.teamVotes || context.teamVotes.length === 0) {\n throw new Error('Team vote strategy requires votes from team members');\n }\n\n // Count votes for each conflict\n const voteResults = this.countVotes(context.teamVotes);\n\n const strategy: ResolutionStrategy = {\n type: 'team_vote',\n confidence: this.calculateVoteConfidence(voteResults),\n reasoning: `Team consensus from ${context.teamVotes.length} votes`,\n votes: context.teamVotes,\n };\n\n // Apply vote results to conflicts\n for (const conflict of conflicts) {\n conflict.resolution = {\n strategy,\n resolvedBy: 'team_consensus',\n resolvedAt: Date.now(),\n notes: `Resolved by ${voteResults.consensus}% consensus`,\n };\n }\n\n return {\n strategy,\n resolvedBy: 'team_consensus',\n resolvedAt: Date.now(),\n notes: `Democratic resolution with ${voteResults.consensus}% agreement`,\n };\n }\n\n /**\n * Strategy: Senior Override\n * Senior developer's choice takes precedence\n */\n private async seniorOverrideStrategy(\n conflicts: MergeConflict[],\n stack1: FrameStack,\n stack2: FrameStack,\n context: ResolutionContext\n ): Promise<ConflictResolution> {\n logger.info('Applying senior_override strategy');\n\n if (context.userRole !== 'senior' && context.userRole !== 'lead') {\n throw new Error('Senior override requires senior or lead role');\n }\n\n // Assume stack1 is the senior's preferred choice\n this.determinePreferredStack(stack1, stack2, context);\n\n const strategy: ResolutionStrategy = {\n type: 'senior_override',\n confidence: 0.95,\n reasoning: `Senior developer (${context.userId}) selected based on experience and architectural knowledge`,\n };\n\n for (const conflict of conflicts) {\n conflict.resolution = {\n strategy,\n resolvedBy: context.userId,\n resolvedAt: Date.now(),\n notes: `Overridden by ${context.userRole} authority`,\n };\n }\n\n return {\n strategy,\n resolvedBy: context.userId,\n resolvedAt: Date.now(),\n notes: `Senior override applied to all ${conflicts.length} conflicts`,\n };\n }\n\n /**\n * Strategy: AI Suggest\n * Uses AI analysis to recommend best resolution\n */\n private async aiSuggestStrategy(\n conflicts: MergeConflict[],\n stack1: FrameStack,\n stack2: FrameStack,\n context: ResolutionContext\n ): Promise<ConflictResolution> {\n logger.info('Applying ai_suggest strategy');\n\n // Analyze frames for quality and effectiveness\n const analysis = await this.analyzeFrameQuality(stack1, stack2);\n\n const strategy: ResolutionStrategy = {\n type: 'ai_suggest',\n confidence: context.aiConfidence || 0.85,\n reasoning: this.generateAIReasoning(analysis),\n };\n\n // Apply AI recommendations to each conflict\n for (const conflict of conflicts) {\n const recommendation = this.getAIRecommendation(conflict, analysis);\n conflict.resolution = {\n strategy,\n resolvedBy: 'ai_system',\n resolvedAt: Date.now(),\n notes: recommendation,\n };\n }\n\n return {\n strategy,\n resolvedBy: 'ai_system',\n resolvedAt: Date.now(),\n notes: `AI analysis with ${strategy.confidence * 100}% confidence`,\n };\n }\n\n /**\n * Strategy: Hybrid\n * Combines multiple strategies based on conflict type\n */\n private async hybridStrategy(\n conflicts: MergeConflict[],\n stack1: FrameStack,\n stack2: FrameStack,\n context: ResolutionContext\n ): Promise<ConflictResolution> {\n logger.info('Applying hybrid strategy');\n\n const strategy: ResolutionStrategy = {\n type: 'hybrid',\n confidence: 0.9,\n reasoning: 'Using optimal strategy for each conflict type',\n };\n\n // Apply different strategies based on conflict type\n for (const conflict of conflicts) {\n let subStrategy: ResolutionStrategy['type'];\n\n switch (conflict.type) {\n case 'parallel_solution':\n // Keep both for parallel solutions\n subStrategy = 'keep_both';\n break;\n\n case 'conflicting_decision':\n // Use AI for decision conflicts\n subStrategy = 'ai_suggest';\n break;\n\n case 'structural_divergence':\n // Use senior override for structural issues\n subStrategy =\n context.userRole === 'senior' || context.userRole === 'lead'\n ? 'senior_override'\n : 'team_vote';\n break;\n\n default:\n subStrategy = 'ai_suggest';\n }\n\n conflict.resolution = {\n strategy: {\n ...strategy,\n reasoning: `${subStrategy} for ${conflict.type}`,\n },\n resolvedBy: context.userId,\n resolvedAt: Date.now(),\n notes: `Hybrid resolution using ${subStrategy}`,\n };\n }\n\n return {\n strategy,\n resolvedBy: context.userId,\n resolvedAt: Date.now(),\n notes: `Hybrid strategy optimized for each conflict type`,\n };\n }\n\n /**\n * Execute the merge based on resolution\n */\n private async executeMerge(\n stack1: FrameStack,\n stack2: FrameStack,\n conflicts: MergeConflict[],\n resolution: ConflictResolution\n ): Promise<MergeResult> {\n const mergedFrameId = uuidv4();\n const rollbackPoint = this.createRollbackPoint(stack1, stack2);\n const notifications: NotificationResult[] = [];\n\n try {\n // Create merged frame stack\n const mergedFrames = this.mergeFrames(\n stack1,\n stack2,\n conflicts,\n resolution\n );\n\n // Validate merge integrity\n const isValid = this.validateMerge(mergedFrames, conflicts);\n\n if (!isValid) {\n throw new Error('Merge validation failed');\n }\n\n // Send notifications\n const notifyResults = await this.sendNotifications(conflicts, resolution);\n notifications.push(...notifyResults);\n\n logger.info('Merge executed successfully', {\n mergedFrameId,\n frameCount: mergedFrames.length,\n strategy: resolution.strategy.type,\n });\n\n return {\n success: true,\n mergedFrameId,\n conflicts,\n resolution,\n rollbackPoint,\n notifications,\n };\n } catch (error) {\n logger.error('Merge execution failed', error as Error);\n\n return {\n success: false,\n conflicts,\n resolution,\n rollbackPoint,\n notifications,\n };\n }\n }\n\n /**\n * Count votes from team members\n */\n private countVotes(votes: TeamVote[]): {\n frame1: number;\n frame2: number;\n both: number;\n neither: number;\n total: number;\n consensus: number;\n } {\n const counts = {\n frame1: 0,\n frame2: 0,\n both: 0,\n neither: 0,\n total: votes.length,\n consensus: 0,\n };\n\n for (const vote of votes) {\n counts[vote.choice]++;\n }\n\n // Calculate consensus percentage\n const maxVotes = Math.max(\n counts.frame1,\n counts.frame2,\n counts.both,\n counts.neither\n );\n counts.consensus = Math.round((maxVotes / counts.total) * 100);\n\n return counts;\n }\n\n /**\n * Calculate confidence based on vote distribution\n */\n private calculateVoteConfidence(voteResults: { consensus: number }): number {\n // High confidence if strong consensus\n if (voteResults.consensus >= 80) return 0.95;\n if (voteResults.consensus >= 60) return 0.75;\n if (voteResults.consensus >= 40) return 0.5;\n return 0.3;\n }\n\n /**\n * Determine winner from vote results\n */\n private determineVoteWinner(\n conflict: MergeConflict,\n voteResults: {\n frame1: number;\n frame2: number;\n both: number;\n neither: number;\n }\n ): string {\n if (voteResults.frame1 > voteResults.frame2) return conflict.frameId1;\n if (voteResults.frame2 > voteResults.frame1) return conflict.frameId2;\n if (voteResults.both > voteResults.neither) return 'both';\n return 'neither';\n }\n\n /**\n * Determine preferred stack for senior override\n */\n private determinePreferredStack(\n stack1: FrameStack,\n stack2: FrameStack,\n context: ResolutionContext\n ): FrameStack {\n // Check if senior owns one of the stacks\n if (stack1.owner === context.userId) return stack1;\n if (stack2.owner === context.userId) return stack2;\n\n // Otherwise, prefer more recent/complete stack\n if (stack1.lastModified > stack2.lastModified) return stack1;\n if (\n stack2.frames.filter((f) => f.state === 'closed').length >\n stack1.frames.filter((f) => f.state === 'closed').length\n ) {\n return stack2;\n }\n\n return stack1;\n }\n\n /**\n * Analyze frame quality for AI suggestions\n */\n private async analyzeFrameQuality(\n stack1: FrameStack,\n stack2: FrameStack\n ): Promise<{\n stack1: { completeness: number; efficiency: number; quality: number };\n stack2: { completeness: number; efficiency: number; quality: number };\n }> {\n const analysis = {\n stack1: {\n completeness: this.calculateCompleteness(stack1),\n efficiency: this.calculateEfficiency(stack1),\n quality: this.calculateQuality(stack1),\n },\n stack2: {\n completeness: this.calculateCompleteness(stack2),\n efficiency: this.calculateEfficiency(stack2),\n quality: this.calculateQuality(stack2),\n },\n };\n\n return analysis;\n }\n\n /**\n * Calculate stack completeness\n */\n private calculateCompleteness(stack: FrameStack): number {\n const closedFrames = stack.frames.filter(\n (f) => f.state === 'closed'\n ).length;\n return closedFrames / stack.frames.length;\n }\n\n /**\n * Calculate stack efficiency\n */\n private calculateEfficiency(stack: FrameStack): number {\n let totalDuration = 0;\n let completedFrames = 0;\n\n for (const frame of stack.frames) {\n if (frame.closed_at && frame.created_at) {\n totalDuration += frame.closed_at - frame.created_at;\n completedFrames++;\n }\n }\n\n if (completedFrames === 0) return 0;\n\n const avgDuration = totalDuration / completedFrames;\n // Normalize: 5 minutes = 1.0, longer = lower score\n return Math.max(0, Math.min(1, 300000 / avgDuration));\n }\n\n /**\n * Calculate stack quality\n */\n private calculateQuality(stack: FrameStack): number {\n let qualityScore = 0;\n\n for (const frame of stack.frames) {\n if (frame.outputs && Object.keys(frame.outputs).length > 0)\n qualityScore += 0.3;\n if (frame.digest_text) qualityScore += 0.3;\n if (frame.state === 'closed') qualityScore += 0.4;\n }\n\n return Math.min(1, qualityScore / stack.frames.length);\n }\n\n /**\n * Generate AI reasoning for resolution\n */\n private generateAIReasoning(analysis: {\n stack1: { completeness: number; efficiency: number; quality: number };\n stack2: { completeness: number; efficiency: number; quality: number };\n }): string {\n const stack1Score =\n analysis.stack1.completeness * 0.3 +\n analysis.stack1.efficiency * 0.3 +\n analysis.stack1.quality * 0.4;\n\n const stack2Score =\n analysis.stack2.completeness * 0.3 +\n analysis.stack2.efficiency * 0.3 +\n analysis.stack2.quality * 0.4;\n\n if (stack1Score > stack2Score) {\n return `Stack 1 shows higher overall quality (${(stack1Score * 100).toFixed(1)}% vs ${(stack2Score * 100).toFixed(1)}%)`;\n } else {\n return `Stack 2 shows higher overall quality (${(stack2Score * 100).toFixed(1)}% vs ${(stack1Score * 100).toFixed(1)}%)`;\n }\n }\n\n /**\n * Get AI recommendation for specific conflict\n */\n private getAIRecommendation(conflict: MergeConflict): string {\n switch (conflict.type) {\n case 'parallel_solution':\n return 'Recommend keeping both solutions for A/B testing';\n\n case 'conflicting_decision':\n return 'Recommend the decision with higher quality score';\n\n case 'structural_divergence':\n return 'Recommend restructuring to accommodate both approaches';\n\n default:\n return 'Recommend manual review for this conflict';\n }\n }\n\n /**\n * Create rollback point before merge\n */\n private createRollbackPoint(\n _stack1: FrameStack,\n _stack2: FrameStack\n ): string {\n const rollbackId = uuidv4();\n\n // Store current state for rollback (would persist in real implementation)\n\n // In real implementation, persist this to database\n logger.info('Created rollback point', { rollbackId });\n\n return rollbackId;\n }\n\n /**\n * Merge frames based on resolution\n */\n private mergeFrames(\n stack1: FrameStack,\n stack2: FrameStack,\n conflicts: MergeConflict[],\n resolution: ConflictResolution\n ): Frame[] {\n const mergedFrames: Frame[] = [];\n const processedIds = new Set<string>();\n\n // Process based on resolution strategy\n switch (resolution.strategy.type) {\n case 'keep_both':\n // Add all frames from both stacks\n mergedFrames.push(...stack1.frames, ...stack2.frames);\n break;\n\n case 'team_vote':\n case 'senior_override':\n case 'ai_suggest':\n // Add frames based on resolution decisions\n for (const frame of stack1.frames) {\n const conflict = conflicts.find((c) => c.frameId1 === frame.frame_id);\n if (!conflict || conflict.resolution?.strategy.type === 'keep_both') {\n mergedFrames.push(frame);\n processedIds.add(frame.frame_id);\n }\n }\n\n for (const frame of stack2.frames) {\n if (!processedIds.has(frame.frame_id)) {\n const conflict = conflicts.find(\n (c) => c.frameId2 === frame.frame_id\n );\n if (\n !conflict ||\n conflict.resolution?.strategy.type === 'keep_both'\n ) {\n mergedFrames.push(frame);\n }\n }\n }\n break;\n\n case 'hybrid':\n // Complex merging based on conflict types\n this.hybridMerge(stack1, stack2, conflicts, mergedFrames);\n break;\n }\n\n return mergedFrames;\n }\n\n /**\n * Hybrid merge implementation\n */\n private hybridMerge(\n stack1: FrameStack,\n stack2: FrameStack,\n conflicts: MergeConflict[],\n mergedFrames: Frame[]\n ): void {\n const conflictMap = new Map<string, MergeConflict>();\n\n for (const conflict of conflicts) {\n conflictMap.set(conflict.frameId1, conflict);\n conflictMap.set(conflict.frameId2, conflict);\n }\n\n // Process each frame based on its conflict type\n for (const frame of [...stack1.frames, ...stack2.frames]) {\n const conflict = conflictMap.get(frame.frame_id);\n\n if (!conflict) {\n // No conflict, add frame\n if (!mergedFrames.find((f) => f.frame_id === frame.frame_id)) {\n mergedFrames.push(frame);\n }\n } else if (conflict.type === 'parallel_solution') {\n // Keep both for parallel solutions\n if (!mergedFrames.find((f) => f.frame_id === frame.frame_id)) {\n mergedFrames.push(frame);\n }\n }\n // Other conflict types handled by resolution\n }\n }\n\n /**\n * Validate merge integrity\n */\n private validateMerge(\n mergedFrames: Frame[],\n conflicts: MergeConflict[]\n ): boolean {\n // Check for duplicate frame IDs\n const ids = new Set<string>();\n for (const frame of mergedFrames) {\n if (ids.has(frame.frame_id)) {\n logger.error('Duplicate frame ID in merge', {\n frameId: frame.frame_id,\n });\n return false;\n }\n ids.add(frame.frame_id);\n }\n\n // Check parent-child relationships\n for (const frame of mergedFrames) {\n if (frame.parent_frame_id) {\n const parent = mergedFrames.find(\n (f) => f.frame_id === frame.parent_frame_id\n );\n if (!parent) {\n logger.warn('Orphaned frame in merge', { frameId: frame.frame_id });\n }\n }\n }\n\n // Check all conflicts have resolutions\n for (const conflict of conflicts) {\n if (!conflict.resolution) {\n logger.error('Unresolved conflict in merge', {\n conflictId: conflict.id,\n });\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Send notifications about merge\n */\n private async sendNotifications(\n conflicts: MergeConflict[],\n resolution: ConflictResolution\n ): Promise<NotificationResult[]> {\n const notifications: NotificationResult[] = [];\n\n // In real implementation, send actual notifications\n // For now, simulate notification sending\n const notification: NotificationResult = {\n userId: resolution.resolvedBy || 'team',\n type: 'in-app',\n sent: true,\n timestamp: Date.now(),\n };\n\n notifications.push(notification);\n\n logger.info('Notifications sent', { count: notifications.length });\n\n return notifications;\n }\n\n /**\n * Store resolution in history\n */\n private storeResolution(\n mergeId: string,\n resolution: ConflictResolution\n ): void {\n this.resolutionHistory.set(mergeId, resolution);\n\n // In real implementation, persist to database\n logger.info('Resolution stored in history', {\n mergeId,\n strategy: resolution.strategy.type,\n });\n }\n\n /**\n * Get resolution history for analysis\n */\n getResolutionHistory(): Map<string, ConflictResolution> {\n return this.resolutionHistory;\n }\n}\n"],
|
|
5
|
-
"mappings": "AAKA,SAAS,MAAM,cAAc;AAW7B,SAAS,wBAAwB;AACjC,SAAS,2BAA2B;AACpC,SAAS,cAAc;AAUhB,MAAM,iBAAiB;AAAA,EACpB;AAAA,EACA;AAAA,EACA,oBAAqD,oBAAI,IAAI;AAAA,EAErE,cAAc;AACZ,SAAK,mBAAmB,IAAI,iBAAiB;AAC7C,SAAK,iBAAiB,IAAI,oBAAoB;AAAA,EAChD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,iBACJ,QACA,QACA,UACA,SACsB;AACtB,UAAM,YAAY,KAAK,iBAAiB,gBAAgB,QAAQ,MAAM;AAEtE,WAAO;AAAA,MACL,aAAa,UAAU,MAAM,oBAAoB,QAAQ;AAAA,MACzD;AAAA,QACE,QAAQ,QAAQ;AAAA,QAChB,UAAU,QAAQ;AAAA,MACpB;AAAA,IACF;AAEA,QAAI;AAEJ,YAAQ,UAAU;AAAA,MAChB,KAAK;AACH,qBAAa,MAAM,KAAK;AAAA,UACtB;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF;AACA;AAAA,MAEF,KAAK;AACH,qBAAa,MAAM,KAAK;AAAA,UACtB;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF;AACA;AAAA,MAEF,KAAK;AACH,qBAAa,MAAM,KAAK;AAAA,UACtB;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF;AACA;AAAA,MAEF,KAAK;AACH,qBAAa,MAAM,KAAK;AAAA,UACtB;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF;AACA;AAAA,MAEF,KAAK;AACH,qBAAa,MAAM,KAAK;AAAA,UACtB;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF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ACA;AAAA,MACF;AAGA,YAAM,UAAU,KAAK,cAAc,cAAc,SAAS;AAE1D,UAAI,CAAC,SAAS;AACZ,cAAM,IAAI,MAAM,yBAAyB;AAAA,MAC3C;AAGA,YAAM,gBAAgB,MAAM,KAAK,kBAAkB,WAAW,UAAU;AACxE,oBAAc,KAAK,GAAG,aAAa;AAEnC,aAAO,KAAK,+BAA+B;AAAA,QACzC;AAAA,QACA,YAAY,aAAa;AAAA,QACzB,UAAU,WAAW,SAAS;AAAA,MAChC,CAAC;AAED,aAAO;AAAA,QACL,SAAS;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF,SAAS,
|
|
4
|
+
"sourcesContent": ["/**\n * Resolution Engine\n * Implements multiple strategies for resolving merge conflicts\n */\n\nimport { v4 as uuidv4 } from 'uuid';\nimport {\n MergeConflict,\n ConflictResolution,\n ResolutionStrategy,\n TeamVote,\n FrameStack,\n MergeResult,\n NotificationResult,\n} from './types.js';\nimport { Frame } from '../context/frame-manager.js';\nimport { ConflictDetector } from './conflict-detector.js';\nimport { StackDiffVisualizer } from './stack-diff.js';\nimport { logger } from '../monitoring/logger.js';\n\nexport interface ResolutionContext {\n userId: string;\n userRole: 'junior' | 'mid' | 'senior' | 'lead';\n teamVotes?: TeamVote[];\n aiConfidence?: number;\n timeConstraint?: number; // milliseconds\n}\n\nexport class ResolutionEngine {\n private conflictDetector: ConflictDetector;\n private diffVisualizer: StackDiffVisualizer;\n private resolutionHistory: Map<string, ConflictResolution> = new Map();\n\n constructor() {\n this.conflictDetector = new ConflictDetector();\n this.diffVisualizer = new StackDiffVisualizer();\n }\n\n /**\n * Resolve conflicts using the specified strategy\n */\n async resolveConflicts(\n stack1: FrameStack,\n stack2: FrameStack,\n strategy: ResolutionStrategy['type'],\n context: ResolutionContext\n ): Promise<MergeResult> {\n const conflicts = this.conflictDetector.detectConflicts(stack1, stack2);\n\n logger.info(\n `Resolving ${conflicts.length} conflicts using ${strategy} strategy`,\n {\n userId: context.userId,\n userRole: context.userRole,\n }\n );\n\n let resolution: ConflictResolution;\n\n switch (strategy) {\n case 'keep_both':\n resolution = await this.keepBothStrategy(\n conflicts,\n stack1,\n stack2,\n context\n );\n break;\n\n case 'team_vote':\n resolution = await this.teamVoteStrategy(\n conflicts,\n stack1,\n stack2,\n context\n );\n break;\n\n case 'senior_override':\n resolution = await this.seniorOverrideStrategy(\n conflicts,\n stack1,\n stack2,\n context\n );\n break;\n\n case 'ai_suggest':\n resolution = await this.aiSuggestStrategy(\n conflicts,\n stack1,\n stack2,\n context\n );\n break;\n\n case 'hybrid':\n resolution = await this.hybridStrategy(\n conflicts,\n stack1,\n stack2,\n context\n );\n break;\n\n default:\n throw new Error(`Unknown resolution strategy: ${strategy}`);\n }\n\n // Execute the merge based on resolution\n const mergeResult = await this.executeMerge(\n stack1,\n stack2,\n conflicts,\n resolution\n );\n\n // Store resolution in history\n this.storeResolution(mergeResult.mergedFrameId || '', resolution);\n\n return mergeResult;\n }\n\n /**\n * Strategy: Keep Both Solutions\n * Creates a merged frame that includes both approaches\n */\n private async keepBothStrategy(\n conflicts: MergeConflict[],\n stack1: FrameStack,\n stack2: FrameStack,\n context: ResolutionContext\n ): Promise<ConflictResolution> {\n logger.info('Applying keep_both strategy');\n\n const strategy: ResolutionStrategy = {\n type: 'keep_both',\n confidence: 0.8,\n reasoning:\n 'Preserving both solutions to maintain all work and allow future evaluation',\n };\n\n // Mark all conflicts as resolved by keeping both\n for (const conflict of conflicts) {\n conflict.resolution = {\n strategy,\n resolvedBy: context.userId,\n resolvedAt: Date.now(),\n notes: 'Both solutions preserved in merged frame',\n };\n }\n\n return {\n strategy,\n resolvedBy: context.userId,\n resolvedAt: Date.now(),\n notes: `Kept all ${stack1.frames.length + stack2.frames.length} frames from both stacks`,\n };\n }\n\n /**\n * Strategy: Team Vote\n * Uses democratic voting to choose between options\n */\n private async teamVoteStrategy(\n conflicts: MergeConflict[],\n stack1: FrameStack,\n stack2: FrameStack,\n context: ResolutionContext\n ): Promise<ConflictResolution> {\n logger.info('Applying team_vote strategy');\n\n if (!context.teamVotes || context.teamVotes.length === 0) {\n throw new Error('Team vote strategy requires votes from team members');\n }\n\n // Count votes for each conflict\n const voteResults = this.countVotes(context.teamVotes);\n\n const strategy: ResolutionStrategy = {\n type: 'team_vote',\n confidence: this.calculateVoteConfidence(voteResults),\n reasoning: `Team consensus from ${context.teamVotes.length} votes`,\n votes: context.teamVotes,\n };\n\n // Apply vote results to conflicts\n for (const conflict of conflicts) {\n conflict.resolution = {\n strategy,\n resolvedBy: 'team_consensus',\n resolvedAt: Date.now(),\n notes: `Resolved by ${voteResults.consensus}% consensus`,\n };\n }\n\n return {\n strategy,\n resolvedBy: 'team_consensus',\n resolvedAt: Date.now(),\n notes: `Democratic resolution with ${voteResults.consensus}% agreement`,\n };\n }\n\n /**\n * Strategy: Senior Override\n * Senior developer's choice takes precedence\n */\n private async seniorOverrideStrategy(\n conflicts: MergeConflict[],\n stack1: FrameStack,\n stack2: FrameStack,\n context: ResolutionContext\n ): Promise<ConflictResolution> {\n logger.info('Applying senior_override strategy');\n\n if (context.userRole !== 'senior' && context.userRole !== 'lead') {\n throw new Error('Senior override requires senior or lead role');\n }\n\n // Assume stack1 is the senior's preferred choice\n this.determinePreferredStack(stack1, stack2, context);\n\n const strategy: ResolutionStrategy = {\n type: 'senior_override',\n confidence: 0.95,\n reasoning: `Senior developer (${context.userId}) selected based on experience and architectural knowledge`,\n };\n\n for (const conflict of conflicts) {\n conflict.resolution = {\n strategy,\n resolvedBy: context.userId,\n resolvedAt: Date.now(),\n notes: `Overridden by ${context.userRole} authority`,\n };\n }\n\n return {\n strategy,\n resolvedBy: context.userId,\n resolvedAt: Date.now(),\n notes: `Senior override applied to all ${conflicts.length} conflicts`,\n };\n }\n\n /**\n * Strategy: AI Suggest\n * Uses AI analysis to recommend best resolution\n */\n private async aiSuggestStrategy(\n conflicts: MergeConflict[],\n stack1: FrameStack,\n stack2: FrameStack,\n context: ResolutionContext\n ): Promise<ConflictResolution> {\n logger.info('Applying ai_suggest strategy');\n\n // Analyze frames for quality and effectiveness\n const analysis = await this.analyzeFrameQuality(stack1, stack2);\n\n const strategy: ResolutionStrategy = {\n type: 'ai_suggest',\n confidence: context.aiConfidence || 0.85,\n reasoning: this.generateAIReasoning(analysis),\n };\n\n // Apply AI recommendations to each conflict\n for (const conflict of conflicts) {\n const recommendation = this.getAIRecommendation(conflict, analysis);\n conflict.resolution = {\n strategy,\n resolvedBy: 'ai_system',\n resolvedAt: Date.now(),\n notes: recommendation,\n };\n }\n\n return {\n strategy,\n resolvedBy: 'ai_system',\n resolvedAt: Date.now(),\n notes: `AI analysis with ${strategy.confidence * 100}% confidence`,\n };\n }\n\n /**\n * Strategy: Hybrid\n * Combines multiple strategies based on conflict type\n */\n private async hybridStrategy(\n conflicts: MergeConflict[],\n stack1: FrameStack,\n stack2: FrameStack,\n context: ResolutionContext\n ): Promise<ConflictResolution> {\n logger.info('Applying hybrid strategy');\n\n const strategy: ResolutionStrategy = {\n type: 'hybrid',\n confidence: 0.9,\n reasoning: 'Using optimal strategy for each conflict type',\n };\n\n // Apply different strategies based on conflict type\n for (const conflict of conflicts) {\n let subStrategy: ResolutionStrategy['type'];\n\n switch (conflict.type) {\n case 'parallel_solution':\n // Keep both for parallel solutions\n subStrategy = 'keep_both';\n break;\n\n case 'conflicting_decision':\n // Use AI for decision conflicts\n subStrategy = 'ai_suggest';\n break;\n\n case 'structural_divergence':\n // Use senior override for structural issues\n subStrategy =\n context.userRole === 'senior' || context.userRole === 'lead'\n ? 'senior_override'\n : 'team_vote';\n break;\n\n default:\n subStrategy = 'ai_suggest';\n }\n\n conflict.resolution = {\n strategy: {\n ...strategy,\n reasoning: `${subStrategy} for ${conflict.type}`,\n },\n resolvedBy: context.userId,\n resolvedAt: Date.now(),\n notes: `Hybrid resolution using ${subStrategy}`,\n };\n }\n\n return {\n strategy,\n resolvedBy: context.userId,\n resolvedAt: Date.now(),\n notes: `Hybrid strategy optimized for each conflict type`,\n };\n }\n\n /**\n * Execute the merge based on resolution\n */\n private async executeMerge(\n stack1: FrameStack,\n stack2: FrameStack,\n conflicts: MergeConflict[],\n resolution: ConflictResolution\n ): Promise<MergeResult> {\n const mergedFrameId = uuidv4();\n const rollbackPoint = this.createRollbackPoint(stack1, stack2);\n const notifications: NotificationResult[] = [];\n\n try {\n // Create merged frame stack\n const mergedFrames = this.mergeFrames(\n stack1,\n stack2,\n conflicts,\n resolution\n );\n\n // Validate merge integrity\n const isValid = this.validateMerge(mergedFrames, conflicts);\n\n if (!isValid) {\n throw new Error('Merge validation failed');\n }\n\n // Send notifications\n const notifyResults = await this.sendNotifications(conflicts, resolution);\n notifications.push(...notifyResults);\n\n logger.info('Merge executed successfully', {\n mergedFrameId,\n frameCount: mergedFrames.length,\n strategy: resolution.strategy.type,\n });\n\n return {\n success: true,\n mergedFrameId,\n conflicts,\n resolution,\n rollbackPoint,\n notifications,\n };\n } catch (error: unknown) {\n logger.error('Merge execution failed', error as Error);\n\n return {\n success: false,\n conflicts,\n resolution,\n rollbackPoint,\n notifications,\n };\n }\n }\n\n /**\n * Count votes from team members\n */\n private countVotes(votes: TeamVote[]): {\n frame1: number;\n frame2: number;\n both: number;\n neither: number;\n total: number;\n consensus: number;\n } {\n const counts = {\n frame1: 0,\n frame2: 0,\n both: 0,\n neither: 0,\n total: votes.length,\n consensus: 0,\n };\n\n for (const vote of votes) {\n counts[vote.choice]++;\n }\n\n // Calculate consensus percentage\n const maxVotes = Math.max(\n counts.frame1,\n counts.frame2,\n counts.both,\n counts.neither\n );\n counts.consensus = Math.round((maxVotes / counts.total) * 100);\n\n return counts;\n }\n\n /**\n * Calculate confidence based on vote distribution\n */\n private calculateVoteConfidence(voteResults: { consensus: number }): number {\n // High confidence if strong consensus\n if (voteResults.consensus >= 80) return 0.95;\n if (voteResults.consensus >= 60) return 0.75;\n if (voteResults.consensus >= 40) return 0.5;\n return 0.3;\n }\n\n /**\n * Determine winner from vote results\n */\n private determineVoteWinner(\n conflict: MergeConflict,\n voteResults: {\n frame1: number;\n frame2: number;\n both: number;\n neither: number;\n }\n ): string {\n if (voteResults.frame1 > voteResults.frame2) return conflict.frameId1;\n if (voteResults.frame2 > voteResults.frame1) return conflict.frameId2;\n if (voteResults.both > voteResults.neither) return 'both';\n return 'neither';\n }\n\n /**\n * Determine preferred stack for senior override\n */\n private determinePreferredStack(\n stack1: FrameStack,\n stack2: FrameStack,\n context: ResolutionContext\n ): FrameStack {\n // Check if senior owns one of the stacks\n if (stack1.owner === context.userId) return stack1;\n if (stack2.owner === context.userId) return stack2;\n\n // Otherwise, prefer more recent/complete stack\n if (stack1.lastModified > stack2.lastModified) return stack1;\n if (\n stack2.frames.filter((f) => f.state === 'closed').length >\n stack1.frames.filter((f) => f.state === 'closed').length\n ) {\n return stack2;\n }\n\n return stack1;\n }\n\n /**\n * Analyze frame quality for AI suggestions\n */\n private async analyzeFrameQuality(\n stack1: FrameStack,\n stack2: FrameStack\n ): Promise<{\n stack1: { completeness: number; efficiency: number; quality: number };\n stack2: { completeness: number; efficiency: number; quality: number };\n }> {\n const analysis = {\n stack1: {\n completeness: this.calculateCompleteness(stack1),\n efficiency: this.calculateEfficiency(stack1),\n quality: this.calculateQuality(stack1),\n },\n stack2: {\n completeness: this.calculateCompleteness(stack2),\n efficiency: this.calculateEfficiency(stack2),\n quality: this.calculateQuality(stack2),\n },\n };\n\n return analysis;\n }\n\n /**\n * Calculate stack completeness\n */\n private calculateCompleteness(stack: FrameStack): number {\n const closedFrames = stack.frames.filter(\n (f) => f.state === 'closed'\n ).length;\n return closedFrames / stack.frames.length;\n }\n\n /**\n * Calculate stack efficiency\n */\n private calculateEfficiency(stack: FrameStack): number {\n let totalDuration = 0;\n let completedFrames = 0;\n\n for (const frame of stack.frames) {\n if (frame.closed_at && frame.created_at) {\n totalDuration += frame.closed_at - frame.created_at;\n completedFrames++;\n }\n }\n\n if (completedFrames === 0) return 0;\n\n const avgDuration = totalDuration / completedFrames;\n // Normalize: 5 minutes = 1.0, longer = lower score\n return Math.max(0, Math.min(1, 300000 / avgDuration));\n }\n\n /**\n * Calculate stack quality\n */\n private calculateQuality(stack: FrameStack): number {\n let qualityScore = 0;\n\n for (const frame of stack.frames) {\n if (frame.outputs && Object.keys(frame.outputs).length > 0)\n qualityScore += 0.3;\n if (frame.digest_text) qualityScore += 0.3;\n if (frame.state === 'closed') qualityScore += 0.4;\n }\n\n return Math.min(1, qualityScore / stack.frames.length);\n }\n\n /**\n * Generate AI reasoning for resolution\n */\n private generateAIReasoning(analysis: {\n stack1: { completeness: number; efficiency: number; quality: number };\n stack2: { completeness: number; efficiency: number; quality: number };\n }): string {\n const stack1Score =\n analysis.stack1.completeness * 0.3 +\n analysis.stack1.efficiency * 0.3 +\n analysis.stack1.quality * 0.4;\n\n const stack2Score =\n analysis.stack2.completeness * 0.3 +\n analysis.stack2.efficiency * 0.3 +\n analysis.stack2.quality * 0.4;\n\n if (stack1Score > stack2Score) {\n return `Stack 1 shows higher overall quality (${(stack1Score * 100).toFixed(1)}% vs ${(stack2Score * 100).toFixed(1)}%)`;\n } else {\n return `Stack 2 shows higher overall quality (${(stack2Score * 100).toFixed(1)}% vs ${(stack1Score * 100).toFixed(1)}%)`;\n }\n }\n\n /**\n * Get AI recommendation for specific conflict\n */\n private getAIRecommendation(conflict: MergeConflict): string {\n switch (conflict.type) {\n case 'parallel_solution':\n return 'Recommend keeping both solutions for A/B testing';\n\n case 'conflicting_decision':\n return 'Recommend the decision with higher quality score';\n\n case 'structural_divergence':\n return 'Recommend restructuring to accommodate both approaches';\n\n default:\n return 'Recommend manual review for this conflict';\n }\n }\n\n /**\n * Create rollback point before merge\n */\n private createRollbackPoint(\n _stack1: FrameStack,\n _stack2: FrameStack\n ): string {\n const rollbackId = uuidv4();\n\n // Store current state for rollback (would persist in real implementation)\n\n // In real implementation, persist this to database\n logger.info('Created rollback point', { rollbackId });\n\n return rollbackId;\n }\n\n /**\n * Merge frames based on resolution\n */\n private mergeFrames(\n stack1: FrameStack,\n stack2: FrameStack,\n conflicts: MergeConflict[],\n resolution: ConflictResolution\n ): Frame[] {\n const mergedFrames: Frame[] = [];\n const processedIds = new Set<string>();\n\n // Process based on resolution strategy\n switch (resolution.strategy.type) {\n case 'keep_both':\n // Add all frames from both stacks\n mergedFrames.push(...stack1.frames, ...stack2.frames);\n break;\n\n case 'team_vote':\n case 'senior_override':\n case 'ai_suggest':\n // Add frames based on resolution decisions\n for (const frame of stack1.frames) {\n const conflict = conflicts.find((c) => c.frameId1 === frame.frame_id);\n if (!conflict || conflict.resolution?.strategy.type === 'keep_both') {\n mergedFrames.push(frame);\n processedIds.add(frame.frame_id);\n }\n }\n\n for (const frame of stack2.frames) {\n if (!processedIds.has(frame.frame_id)) {\n const conflict = conflicts.find(\n (c) => c.frameId2 === frame.frame_id\n );\n if (\n !conflict ||\n conflict.resolution?.strategy.type === 'keep_both'\n ) {\n mergedFrames.push(frame);\n }\n }\n }\n break;\n\n case 'hybrid':\n // Complex merging based on conflict types\n this.hybridMerge(stack1, stack2, conflicts, mergedFrames);\n break;\n }\n\n return mergedFrames;\n }\n\n /**\n * Hybrid merge implementation\n */\n private hybridMerge(\n stack1: FrameStack,\n stack2: FrameStack,\n conflicts: MergeConflict[],\n mergedFrames: Frame[]\n ): void {\n const conflictMap = new Map<string, MergeConflict>();\n\n for (const conflict of conflicts) {\n conflictMap.set(conflict.frameId1, conflict);\n conflictMap.set(conflict.frameId2, conflict);\n }\n\n // Process each frame based on its conflict type\n for (const frame of [...stack1.frames, ...stack2.frames]) {\n const conflict = conflictMap.get(frame.frame_id);\n\n if (!conflict) {\n // No conflict, add frame\n if (!mergedFrames.find((f) => f.frame_id === frame.frame_id)) {\n mergedFrames.push(frame);\n }\n } else if (conflict.type === 'parallel_solution') {\n // Keep both for parallel solutions\n if (!mergedFrames.find((f) => f.frame_id === frame.frame_id)) {\n mergedFrames.push(frame);\n }\n }\n // Other conflict types handled by resolution\n }\n }\n\n /**\n * Validate merge integrity\n */\n private validateMerge(\n mergedFrames: Frame[],\n conflicts: MergeConflict[]\n ): boolean {\n // Check for duplicate frame IDs\n const ids = new Set<string>();\n for (const frame of mergedFrames) {\n if (ids.has(frame.frame_id)) {\n logger.error('Duplicate frame ID in merge', {\n frameId: frame.frame_id,\n });\n return false;\n }\n ids.add(frame.frame_id);\n }\n\n // Check parent-child relationships\n for (const frame of mergedFrames) {\n if (frame.parent_frame_id) {\n const parent = mergedFrames.find(\n (f) => f.frame_id === frame.parent_frame_id\n );\n if (!parent) {\n logger.warn('Orphaned frame in merge', { frameId: frame.frame_id });\n }\n }\n }\n\n // Check all conflicts have resolutions\n for (const conflict of conflicts) {\n if (!conflict.resolution) {\n logger.error('Unresolved conflict in merge', {\n conflictId: conflict.id,\n });\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Send notifications about merge\n */\n private async sendNotifications(\n conflicts: MergeConflict[],\n resolution: ConflictResolution\n ): Promise<NotificationResult[]> {\n const notifications: NotificationResult[] = [];\n\n // In real implementation, send actual notifications\n // For now, simulate notification sending\n const notification: NotificationResult = {\n userId: resolution.resolvedBy || 'team',\n type: 'in-app',\n sent: true,\n timestamp: Date.now(),\n };\n\n notifications.push(notification);\n\n logger.info('Notifications sent', { count: notifications.length });\n\n return notifications;\n }\n\n /**\n * Store resolution in history\n */\n private storeResolution(\n mergeId: string,\n resolution: ConflictResolution\n ): void {\n this.resolutionHistory.set(mergeId, resolution);\n\n // In real implementation, persist to database\n logger.info('Resolution stored in history', {\n mergeId,\n strategy: resolution.strategy.type,\n });\n }\n\n /**\n * Get resolution history for analysis\n */\n getResolutionHistory(): Map<string, ConflictResolution> {\n return this.resolutionHistory;\n }\n}\n"],
|
|
5
|
+
"mappings": "AAKA,SAAS,MAAM,cAAc;AAW7B,SAAS,wBAAwB;AACjC,SAAS,2BAA2B;AACpC,SAAS,cAAc;AAUhB,MAAM,iBAAiB;AAAA,EACpB;AAAA,EACA;AAAA,EACA,oBAAqD,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AC1C;AAAA,MACA,UAAU,WAAW,SAAS;AAAA,IAChC,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,uBAAwD;AACtD,WAAO,KAAK;AAAA,EACd;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/core/monitoring/error-handler.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Comprehensive error handling for StackMemory CLI\n */\n\nimport { logger } from './logger.js';\n\nexport enum ErrorCode {\n // Authentication errors\n AUTH_FAILED = 'AUTH_FAILED',\n TOKEN_EXPIRED = 'TOKEN_EXPIRED',\n INVALID_CREDENTIALS = 'INVALID_CREDENTIALS',\n\n // File system errors\n FILE_NOT_FOUND = 'FILE_NOT_FOUND',\n PERMISSION_DENIED = 'PERMISSION_DENIED',\n DISK_FULL = 'DISK_FULL',\n\n // Git operation errors\n NOT_GIT_REPO = 'NOT_GIT_REPO',\n GIT_COMMAND_FAILED = 'GIT_COMMAND_FAILED',\n INVALID_BRANCH = 'INVALID_BRANCH',\n\n // Database errors\n DB_CONNECTION_FAILED = 'DB_CONNECTION_FAILED',\n DB_QUERY_FAILED = 'DB_QUERY_FAILED',\n DB_CORRUPTION = 'DB_CORRUPTION',\n\n // Network errors\n NETWORK_ERROR = 'NETWORK_ERROR',\n API_ERROR = 'API_ERROR',\n TIMEOUT = 'TIMEOUT',\n\n // Validation errors\n INVALID_INPUT = 'INVALID_INPUT',\n VALIDATION_FAILED = 'VALIDATION_FAILED',\n\n // General errors\n UNKNOWN_ERROR = 'UNKNOWN_ERROR',\n OPERATION_FAILED = 'OPERATION_FAILED',\n CONFIGURATION_ERROR = 'CONFIGURATION_ERROR',\n}\n\nexport class StackMemoryError extends Error {\n public readonly code: ErrorCode;\n public readonly context: Record<string, unknown>;\n public readonly userMessage: string;\n public readonly recoverable: boolean;\n\n constructor(\n code: ErrorCode,\n message: string,\n userMessage?: string,\n context: Record<string, unknown> = {},\n recoverable: boolean = false,\n cause?: Error\n ) {\n super(message);\n this.name = 'StackMemoryError';\n this.code = code;\n this.context = context;\n this.userMessage = userMessage || this.getDefaultUserMessage(code);\n this.recoverable = recoverable;\n\n if (cause && Error.captureStackTrace) {\n Error.captureStackTrace(this, StackMemoryError);\n }\n\n // Log the error\n logger.error(message, cause, {\n code,\n context,\n recoverable,\n userMessage: this.userMessage,\n });\n }\n\n private getDefaultUserMessage(code: ErrorCode): string {\n switch (code) {\n case ErrorCode.AUTH_FAILED:\n return 'Authentication failed. Please check your credentials and try again.';\n case ErrorCode.NOT_GIT_REPO:\n return 'This command requires a git repository. Please run it from within a git repository.';\n case ErrorCode.PERMISSION_DENIED:\n return 'Permission denied. Please check file permissions or run with appropriate privileges.';\n case ErrorCode.NETWORK_ERROR:\n return 'Network error. Please check your internet connection and try again.';\n case ErrorCode.INVALID_INPUT:\n return 'Invalid input provided. Please check your command and try again.';\n case ErrorCode.DB_CONNECTION_FAILED:\n return 'Database connection failed. Please try again or contact support if the issue persists.';\n case ErrorCode.GIT_COMMAND_FAILED:\n return 'Git operation failed. Please ensure your repository is in a valid state.';\n default:\n return 'An unexpected error occurred. Please try again or contact support.';\n }\n }\n\n static fromNodeError(\n nodeError: NodeJS.ErrnoException,\n context: Record<string, unknown> = {}\n ): StackMemoryError {\n const code = nodeError.code;\n\n switch (code) {\n case 'ENOENT':\n return new StackMemoryError(\n ErrorCode.FILE_NOT_FOUND,\n `File or directory not found: ${nodeError.path}`,\n 'The requested file or directory was not found.',\n { ...context, path: nodeError.path },\n false,\n nodeError\n );\n\n case 'EACCES':\n case 'EPERM':\n return new StackMemoryError(\n ErrorCode.PERMISSION_DENIED,\n `Permission denied: ${nodeError.path}`,\n 'Permission denied. Please check file permissions.',\n { ...context, path: nodeError.path },\n true,\n nodeError\n );\n\n case 'ENOSPC':\n return new StackMemoryError(\n ErrorCode.DISK_FULL,\n 'No space left on device',\n 'Insufficient disk space. Please free up space and try again.',\n context,\n true,\n nodeError\n );\n\n case 'ETIMEDOUT':\n return new StackMemoryError(\n ErrorCode.TIMEOUT,\n 'Operation timed out',\n 'The operation timed out. Please try again.',\n context,\n true,\n nodeError\n );\n\n default:\n return new StackMemoryError(\n ErrorCode.UNKNOWN_ERROR,\n nodeError.message,\n 'An unexpected system error occurred.',\n { ...context, nodeErrorCode: code },\n false,\n nodeError\n );\n }\n }\n}\n\nexport class ErrorHandler {\n private static retryMap = new Map<string, number>();\n private static readonly MAX_RETRIES = 3;\n\n static handle(error: unknown, operation: string): never {\n if (error instanceof StackMemoryError) {\n // Already a well-formed StackMemory error\n console.error(`\u274C ${error.userMessage}`);\n\n if (error.recoverable) {\n console.error('\uD83D\uDCA1 This error may be recoverable. Please try again.');\n }\n\n process.exit(1);\n }\n\n if (error instanceof Error) {\n // Convert Node.js error to StackMemoryError\n let stackMemoryError: StackMemoryError;\n\n if ('code' in error && typeof error.code === 'string') {\n stackMemoryError = StackMemoryError.fromNodeError(\n error as NodeJS.ErrnoException,\n { operation }\n );\n } else {\n stackMemoryError = new StackMemoryError(\n ErrorCode.OPERATION_FAILED,\n `Operation '${operation}' failed: ${error.message}`,\n `Operation failed: ${error.message}`,\n { operation },\n false,\n error\n );\n }\n\n console.error(`\u274C ${stackMemoryError.userMessage}`);\n if (stackMemoryError.recoverable) {\n console.error('\uD83D\uDCA1 This error may be recoverable. Please try again.');\n }\n\n process.exit(1);\n }\n\n // Unknown error type\n const unknownError = new StackMemoryError(\n ErrorCode.UNKNOWN_ERROR,\n `Unknown error in operation '${operation}': ${String(error)}`,\n 'An unexpected error occurred.',\n { operation, errorType: typeof error },\n false\n );\n\n console.error(`\u274C ${unknownError.userMessage}`);\n process.exit(1);\n }\n\n static async safeExecute<T>(\n operation: () => Promise<T> | T,\n operationName: string,\n fallback?: T\n ): Promise<T | undefined> {\n try {\n return await operation();\n } catch (error) {\n if (fallback !== undefined) {\n logger.warn(`Operation '${operationName}' failed, using fallback`, {\n error: String(error),\n });\n return fallback;\n }\n\n ErrorHandler.handle(error, operationName);\n }\n }\n\n static async withRetry<T>(\n operation: () => Promise<T> | T,\n operationName: string,\n maxRetries: number = ErrorHandler.MAX_RETRIES\n ): Promise<T> {\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const result = await operation();\n // Clear retry count on success\n ErrorHandler.retryMap.delete(operationName);\n return result;\n } catch (error) {\n lastError = error;\n\n if (error instanceof StackMemoryError && !error.recoverable) {\n // Don't retry non-recoverable errors\n ErrorHandler.handle(error, operationName);\n }\n\n if (attempt === maxRetries) {\n break;\n }\n\n const delay = Math.min(1000 * Math.pow(2, attempt - 1), 5000); // Exponential backoff\n logger.warn(\n `Attempt ${attempt}/${maxRetries} failed for '${operationName}', retrying in ${delay}ms`,\n {\n error: String(error),\n }\n );\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n ErrorHandler.handle(\n lastError,\n `${operationName} (after ${maxRetries} attempts)`\n );\n }\n\n static createCircuitBreaker<T>(\n operation: () => Promise<T> | T,\n operationName: string,\n threshold: number = 5\n ) {\n let failures = 0;\n let lastFailure = 0;\n const resetTimeout = 30000; // 30 seconds\n\n return async (): Promise<T> => {\n const now = Date.now();\n\n // Reset circuit breaker after timeout\n if (now - lastFailure > resetTimeout) {\n failures = 0;\n }\n\n // Circuit is open (too many failures)\n if (failures >= threshold) {\n throw new StackMemoryError(\n ErrorCode.OPERATION_FAILED,\n `Circuit breaker open for '${operationName}'`,\n `Operation temporarily unavailable. Please try again later.`,\n { operationName, failures, threshold },\n true\n );\n }\n\n try {\n const result = await operation();\n failures = 0; // Reset on success\n return result;\n } catch (error) {\n failures++;\n lastFailure = now;\n throw error;\n }\n };\n }\n}\n\n// Utility functions for common error scenarios\nexport const validateInput = (\n value: unknown,\n name: string,\n validator: (val: unknown) => boolean\n): asserts value is NonNullable<unknown> => {\n if (!validator(value)) {\n throw new StackMemoryError(\n ErrorCode.INVALID_INPUT,\n `Invalid ${name}: ${String(value)}`,\n `Please provide a valid ${name}.`,\n { name, value },\n true\n );\n }\n};\n\nexport const validateEmail = (email: string): asserts email is string => {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n if (!emailRegex.test(email) || email.length > 254) {\n throw new StackMemoryError(\n ErrorCode.INVALID_INPUT,\n `Invalid email format: ${email}`,\n 'Please provide a valid email address.',\n { email },\n true\n );\n }\n};\n\nexport const validatePath = (filePath: string): asserts filePath is string => {\n if (!filePath || filePath.includes('..') || filePath.includes('\\0')) {\n throw new StackMemoryError(\n ErrorCode.INVALID_INPUT,\n `Invalid path: ${filePath}`,\n 'Invalid file path provided.',\n { path: filePath },\n true\n );\n }\n};\n"],
|
|
5
|
-
"mappings": "AAIA,SAAS,cAAc;AAEhB,IAAK,YAAL,kBAAKA,eAAL;AAEL,EAAAA,WAAA,iBAAc;AACd,EAAAA,WAAA,mBAAgB;AAChB,EAAAA,WAAA,yBAAsB;AAGtB,EAAAA,WAAA,oBAAiB;AACjB,EAAAA,WAAA,uBAAoB;AACpB,EAAAA,WAAA,eAAY;AAGZ,EAAAA,WAAA,kBAAe;AACf,EAAAA,WAAA,wBAAqB;AACrB,EAAAA,WAAA,oBAAiB;AAGjB,EAAAA,WAAA,0BAAuB;AACvB,EAAAA,WAAA,qBAAkB;AAClB,EAAAA,WAAA,mBAAgB;AAGhB,EAAAA,WAAA,mBAAgB;AAChB,EAAAA,WAAA,eAAY;AACZ,EAAAA,WAAA,aAAU;AAGV,EAAAA,WAAA,mBAAgB;AAChB,EAAAA,WAAA,uBAAoB;AAGpB,EAAAA,WAAA,mBAAgB;AAChB,EAAAA,WAAA,sBAAmB;AACnB,EAAAA,WAAA,yBAAsB;AAjCZ,SAAAA;AAAA,GAAA;AAoCL,MAAM,yBAAyB,MAAM;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YACE,MACA,SACA,aACA,UAAmC,CAAC,GACpC,c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W,EAAE;AAC7C,YAAQ,KAAK,CAAC;AAAA,EAChB;AAAA,EAEA,aAAa,YACX,WACA,eACA,UACwB;AACxB,QAAI;AACF,aAAO,MAAM,UAAU;AAAA,IACzB,SAAS,
|
|
4
|
+
"sourcesContent": ["/**\n * Comprehensive error handling for StackMemory CLI\n */\n\nimport { logger } from './logger.js';\n\nexport enum ErrorCode {\n // Authentication errors\n AUTH_FAILED = 'AUTH_FAILED',\n TOKEN_EXPIRED = 'TOKEN_EXPIRED',\n INVALID_CREDENTIALS = 'INVALID_CREDENTIALS',\n\n // File system errors\n FILE_NOT_FOUND = 'FILE_NOT_FOUND',\n PERMISSION_DENIED = 'PERMISSION_DENIED',\n DISK_FULL = 'DISK_FULL',\n\n // Git operation errors\n NOT_GIT_REPO = 'NOT_GIT_REPO',\n GIT_COMMAND_FAILED = 'GIT_COMMAND_FAILED',\n INVALID_BRANCH = 'INVALID_BRANCH',\n\n // Database errors\n DB_CONNECTION_FAILED = 'DB_CONNECTION_FAILED',\n DB_QUERY_FAILED = 'DB_QUERY_FAILED',\n DB_CORRUPTION = 'DB_CORRUPTION',\n\n // Network errors\n NETWORK_ERROR = 'NETWORK_ERROR',\n API_ERROR = 'API_ERROR',\n TIMEOUT = 'TIMEOUT',\n\n // Validation errors\n INVALID_INPUT = 'INVALID_INPUT',\n VALIDATION_FAILED = 'VALIDATION_FAILED',\n\n // General errors\n UNKNOWN_ERROR = 'UNKNOWN_ERROR',\n OPERATION_FAILED = 'OPERATION_FAILED',\n CONFIGURATION_ERROR = 'CONFIGURATION_ERROR',\n}\n\nexport class StackMemoryError extends Error {\n public readonly code: ErrorCode;\n public readonly context: Record<string, unknown>;\n public readonly userMessage: string;\n public readonly recoverable: boolean;\n\n constructor(\n code: ErrorCode,\n message: string,\n userMessage?: string,\n context: Record<string, unknown> = {},\n recoverable: boolean = false,\n cause?: Error\n ) {\n super(message);\n this.name = 'StackMemoryError';\n this.code = code;\n this.context = context;\n this.userMessage = userMessage || this.getDefaultUserMessage(code);\n this.recoverable = recoverable;\n\n if (cause && Error.captureStackTrace) {\n Error.captureStackTrace(this, StackMemoryError);\n }\n\n // Log the error\n logger.error(message, cause, {\n code,\n context,\n recoverable,\n userMessage: this.userMessage,\n });\n }\n\n private getDefaultUserMessage(code: ErrorCode): string {\n switch (code) {\n case ErrorCode.AUTH_FAILED:\n return 'Authentication failed. Please check your credentials and try again.';\n case ErrorCode.NOT_GIT_REPO:\n return 'This command requires a git repository. Please run it from within a git repository.';\n case ErrorCode.PERMISSION_DENIED:\n return 'Permission denied. Please check file permissions or run with appropriate privileges.';\n case ErrorCode.NETWORK_ERROR:\n return 'Network error. Please check your internet connection and try again.';\n case ErrorCode.INVALID_INPUT:\n return 'Invalid input provided. Please check your command and try again.';\n case ErrorCode.DB_CONNECTION_FAILED:\n return 'Database connection failed. Please try again or contact support if the issue persists.';\n case ErrorCode.GIT_COMMAND_FAILED:\n return 'Git operation failed. Please ensure your repository is in a valid state.';\n default:\n return 'An unexpected error occurred. Please try again or contact support.';\n }\n }\n\n static fromNodeError(\n nodeError: NodeJS.ErrnoException,\n context: Record<string, unknown> = {}\n ): StackMemoryError {\n const code = nodeError.code;\n\n switch (code) {\n case 'ENOENT':\n return new StackMemoryError(\n ErrorCode.FILE_NOT_FOUND,\n `File or directory not found: ${nodeError.path}`,\n 'The requested file or directory was not found.',\n { ...context, path: nodeError.path },\n false,\n nodeError\n );\n\n case 'EACCES':\n case 'EPERM':\n return new StackMemoryError(\n ErrorCode.PERMISSION_DENIED,\n `Permission denied: ${nodeError.path}`,\n 'Permission denied. Please check file permissions.',\n { ...context, path: nodeError.path },\n true,\n nodeError\n );\n\n case 'ENOSPC':\n return new StackMemoryError(\n ErrorCode.DISK_FULL,\n 'No space left on device',\n 'Insufficient disk space. Please free up space and try again.',\n context,\n true,\n nodeError\n );\n\n case 'ETIMEDOUT':\n return new StackMemoryError(\n ErrorCode.TIMEOUT,\n 'Operation timed out',\n 'The operation timed out. Please try again.',\n context,\n true,\n nodeError\n );\n\n default:\n return new StackMemoryError(\n ErrorCode.UNKNOWN_ERROR,\n nodeError.message,\n 'An unexpected system error occurred.',\n { ...context, nodeErrorCode: code },\n false,\n nodeError\n );\n }\n }\n}\n\nexport class ErrorHandler {\n private static retryMap = new Map<string, number>();\n private static readonly MAX_RETRIES = 3;\n\n static handle(error: unknown, operation: string): never {\n if (error instanceof StackMemoryError) {\n // Already a well-formed StackMemory error\n console.error(`\u274C ${error.userMessage}`);\n\n if (error.recoverable) {\n console.error('\uD83D\uDCA1 This error may be recoverable. Please try again.');\n }\n\n process.exit(1);\n }\n\n if (error instanceof Error) {\n // Convert Node.js error to StackMemoryError\n let stackMemoryError: StackMemoryError;\n\n if ('code' in error && typeof error.code === 'string') {\n stackMemoryError = StackMemoryError.fromNodeError(\n error as NodeJS.ErrnoException,\n { operation }\n );\n } else {\n stackMemoryError = new StackMemoryError(\n ErrorCode.OPERATION_FAILED,\n `Operation '${operation}' failed: ${error.message}`,\n `Operation failed: ${error.message}`,\n { operation },\n false,\n error\n );\n }\n\n console.error(`\u274C ${stackMemoryError.userMessage}`);\n if (stackMemoryError.recoverable) {\n console.error('\uD83D\uDCA1 This error may be recoverable. Please try again.');\n }\n\n process.exit(1);\n }\n\n // Unknown error type\n const unknownError = new StackMemoryError(\n ErrorCode.UNKNOWN_ERROR,\n `Unknown error in operation '${operation}': ${String(error)}`,\n 'An unexpected error occurred.',\n { operation, errorType: typeof error },\n false\n );\n\n console.error(`\u274C ${unknownError.userMessage}`);\n process.exit(1);\n }\n\n static async safeExecute<T>(\n operation: () => Promise<T> | T,\n operationName: string,\n fallback?: T\n ): Promise<T | undefined> {\n try {\n return await operation();\n } catch (error: unknown) {\n if (fallback !== undefined) {\n logger.warn(`Operation '${operationName}' failed, using fallback`, {\n error: String(error),\n });\n return fallback;\n }\n\n ErrorHandler.handle(error, operationName);\n }\n }\n\n static async withRetry<T>(\n operation: () => Promise<T> | T,\n operationName: string,\n maxRetries: number = ErrorHandler.MAX_RETRIES\n ): Promise<T> {\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n const result = await operation();\n // Clear retry count on success\n ErrorHandler.retryMap.delete(operationName);\n return result;\n } catch (error: unknown) {\n lastError = error;\n\n if (error instanceof StackMemoryError && !error.recoverable) {\n // Don't retry non-recoverable errors\n ErrorHandler.handle(error, operationName);\n }\n\n if (attempt === maxRetries) {\n break;\n }\n\n const delay = Math.min(1000 * Math.pow(2, attempt - 1), 5000); // Exponential backoff\n logger.warn(\n `Attempt ${attempt}/${maxRetries} failed for '${operationName}', retrying in ${delay}ms`,\n {\n error: String(error),\n }\n );\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n ErrorHandler.handle(\n lastError,\n `${operationName} (after ${maxRetries} attempts)`\n );\n }\n\n static createCircuitBreaker<T>(\n operation: () => Promise<T> | T,\n operationName: string,\n threshold: number = 5\n ) {\n let failures = 0;\n let lastFailure = 0;\n const resetTimeout = 30000; // 30 seconds\n\n return async (): Promise<T> => {\n const now = Date.now();\n\n // Reset circuit breaker after timeout\n if (now - lastFailure > resetTimeout) {\n failures = 0;\n }\n\n // Circuit is open (too many failures)\n if (failures >= threshold) {\n throw new StackMemoryError(\n ErrorCode.OPERATION_FAILED,\n `Circuit breaker open for '${operationName}'`,\n `Operation temporarily unavailable. Please try again later.`,\n { operationName, failures, threshold },\n true\n );\n }\n\n try {\n const result = await operation();\n failures = 0; // Reset on success\n return result;\n } catch (error: unknown) {\n failures++;\n lastFailure = now;\n throw error;\n }\n };\n }\n}\n\n// Utility functions for common error scenarios\nexport const validateInput = (\n value: unknown,\n name: string,\n validator: (val: unknown) => boolean\n): asserts value is NonNullable<unknown> => {\n if (!validator(value)) {\n throw new StackMemoryError(\n ErrorCode.INVALID_INPUT,\n `Invalid ${name}: ${String(value)}`,\n `Please provide a valid ${name}.`,\n { name, value },\n true\n );\n }\n};\n\nexport const validateEmail = (email: string): asserts email is string => {\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n if (!emailRegex.test(email) || email.length > 254) {\n throw new StackMemoryError(\n ErrorCode.INVALID_INPUT,\n `Invalid email format: ${email}`,\n 'Please provide a valid email address.',\n { email },\n true\n );\n }\n};\n\nexport const validatePath = (filePath: string): asserts filePath is string => {\n if (!filePath || filePath.includes('..') || filePath.includes('\\0')) {\n throw new StackMemoryError(\n ErrorCode.INVALID_INPUT,\n `Invalid path: ${filePath}`,\n 'Invalid file path provided.',\n { path: filePath },\n true\n );\n }\n};\n"],
|
|
5
|
+
"mappings": "AAIA,SAAS,cAAc;AAEhB,IAAK,YAAL,kBAAKA,eAAL;AAEL,EAAAA,WAAA,iBAAc;AACd,EAAAA,WAAA,mBAAgB;AAChB,EAAAA,WAAA,yBAAsB;AAGtB,EAAAA,WAAA,oBAAiB;AACjB,EAAAA,WAAA,uBAAoB;AACpB,EAAAA,WAAA,eAAY;AAGZ,EAAAA,WAAA,kBAAe;AACf,EAAAA,WAAA,wBAAqB;AACrB,EAAAA,WAAA,oBAAiB;AAGjB,EAAAA,WAAA,0BAAuB;AACvB,EAAAA,WAAA,qBAAkB;AAClB,EAAAA,WAAA,mBAAgB;AAGhB,EAAAA,WAAA,mBAAgB;AAChB,EAAAA,WAAA,eAAY;AACZ,EAAAA,WAAA,aAAU;AAGV,EAAAA,WAAA,mBAAgB;AAChB,EAAAA,WAAA,uBAAoB;AAGpB,EAAAA,WAAA,mBAAgB;AAChB,EAAAA,WAAA,sBAAmB;AACnB,EAAAA,WAAA,yBAAsB;AAjCZ,SAAAA;AAAA,GAAA;AAoCL,MAAM,yBAAyB,MAAM;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YACE,MACA,SACA,aACA,UAAmC,CAAC,GACpC,cAAuB,OACvB,OACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,UAAU;AACf,SAAK,cAAc,eAAe,KAAK,sBAAsB,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,6BAA6B,aAAa;AAAA,UAC1C;AAAA,UACA,EAAE,eAAe,UAAU,UAAU;AAAA,UACrC;AAAA,QACF;AAAA,MACF;AAEA,UAAI;AACF,cAAM,SAAS,MAAM,UAAU;AAC/B,mBAAW;AACX,eAAO;AAAA,MACT,SAAS,OAAgB;AACvB;AACA,sBAAc;AACd,cAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;AAGO,MAAM,gBAAgB,CAC3B,OACA,MACA,cAC0C;AAC1C,MAAI,CAAC,UAAU,KAAK,GAAG;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,MACA,WAAW,IAAI,KAAK,OAAO,KAAK,CAAC;AAAA,MACjC,0BAA0B,IAAI;AAAA,MAC9B,EAAE,MAAM,MAAM;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;AAEO,MAAM,gBAAgB,CAAC,UAA2C;AACvE,QAAM,aAAa;AACnB,MAAI,CAAC,WAAW,KAAK,KAAK,KAAK,MAAM,SAAS,KAAK;AACjD,UAAM,IAAI;AAAA,MACR;AAAA,MACA,yBAAyB,KAAK;AAAA,MAC9B;AAAA,MACA,EAAE,MAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;AAEO,MAAM,eAAe,CAAC,aAAiD;AAC5E,MAAI,CAAC,YAAY,SAAS,SAAS,IAAI,KAAK,SAAS,SAAS,IAAI,GAAG;AACnE,UAAM,IAAI;AAAA,MACR;AAAA,MACA,iBAAiB,QAAQ;AAAA,MACzB;AAAA,MACA,EAAE,MAAM,SAAS;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": ["ErrorCode"]
|
|
7
7
|
}
|
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
import * as fs from "fs";
|
|
2
2
|
import * as path from "path";
|
|
3
|
+
function getEnv(key, defaultValue) {
|
|
4
|
+
const value = process.env[key];
|
|
5
|
+
if (value === void 0) {
|
|
6
|
+
if (defaultValue !== void 0) return defaultValue;
|
|
7
|
+
throw new Error(`Environment variable ${key} is required`);
|
|
8
|
+
}
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
function getOptionalEnv(key) {
|
|
12
|
+
return process.env[key];
|
|
13
|
+
}
|
|
3
14
|
var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
|
|
4
15
|
LogLevel2[LogLevel2["ERROR"] = 0] = "ERROR";
|
|
5
16
|
LogLevel2[LogLevel2["WARN"] = 1] = "WARN";
|
|
@@ -13,7 +24,7 @@ class Logger {
|
|
|
13
24
|
logFile;
|
|
14
25
|
fileLoggingDisabledNotified = false;
|
|
15
26
|
constructor() {
|
|
16
|
-
const envLevel = process.env
|
|
27
|
+
const envLevel = process.env["STACKMEMORY_LOG_LEVEL"]?.toUpperCase();
|
|
17
28
|
switch (envLevel) {
|
|
18
29
|
case "ERROR":
|
|
19
30
|
this.logLevel = 0 /* ERROR */;
|
|
@@ -27,8 +38,8 @@ class Logger {
|
|
|
27
38
|
default:
|
|
28
39
|
this.logLevel = 2 /* INFO */;
|
|
29
40
|
}
|
|
30
|
-
if (this.logLevel === 3 /* DEBUG */ || process.env
|
|
31
|
-
this.logFile = process.env
|
|
41
|
+
if (this.logLevel === 3 /* DEBUG */ || process.env["STACKMEMORY_LOG_FILE"]) {
|
|
42
|
+
this.logFile = process.env["STACKMEMORY_LOG_FILE"] || path.join(process.env["HOME"] || ".", ".stackmemory", "logs", "cli.log");
|
|
32
43
|
this.ensureLogDirectory();
|
|
33
44
|
}
|
|
34
45
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/core/monitoring/logger.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Structured logging utility for StackMemory CLI\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nexport enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3,\n}\n\ninterface LogEntry {\n timestamp: string;\n level: LogLevel;\n message: string;\n context?: Record<string, unknown>;\n error?: Error;\n}\n\nexport class Logger {\n private static instance: Logger;\n private logLevel: LogLevel = LogLevel.INFO;\n private logFile?: string;\n private fileLoggingDisabledNotified = false;\n\n private constructor() {\n // Set log level from environment\n const envLevel = process.env
|
|
5
|
-
"mappings": "AAIA,YAAY,QAAQ;AACpB,YAAY,UAAU;
|
|
4
|
+
"sourcesContent": ["/**\n * Structured logging utility for StackMemory CLI\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\n// Type-safe environment variable access\nfunction getEnv(key: string, defaultValue?: string): string {\n const value = process.env[key];\n if (value === undefined) {\n if (defaultValue !== undefined) return defaultValue;\n throw new Error(`Environment variable ${key} is required`);\n }\n return value;\n}\n\nfunction getOptionalEnv(key: string): string | undefined {\n return process.env[key];\n}\n\n\nexport enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3,\n}\n\ninterface LogEntry {\n timestamp: string;\n level: LogLevel;\n message: string;\n context?: Record<string, unknown>;\n error?: Error;\n}\n\nexport class Logger {\n private static instance: Logger;\n private logLevel: LogLevel = LogLevel.INFO;\n private logFile?: string;\n private fileLoggingDisabledNotified = false;\n\n private constructor() {\n // Set log level from environment\n const envLevel = process.env['STACKMEMORY_LOG_LEVEL']?.toUpperCase();\n switch (envLevel) {\n case 'ERROR':\n this.logLevel = LogLevel.ERROR;\n break;\n case 'WARN':\n this.logLevel = LogLevel.WARN;\n break;\n case 'DEBUG':\n this.logLevel = LogLevel.DEBUG;\n break;\n default:\n this.logLevel = LogLevel.INFO;\n }\n\n // Set up log file if in debug mode or if specified\n if (this.logLevel === LogLevel.DEBUG || process.env['STACKMEMORY_LOG_FILE']) {\n this.logFile =\n process.env['STACKMEMORY_LOG_FILE'] ||\n path.join(process.env['HOME'] || '.', '.stackmemory', 'logs', 'cli.log');\n this.ensureLogDirectory();\n }\n }\n\n static getInstance(): Logger {\n if (!Logger.instance) {\n Logger.instance = new Logger();\n }\n return Logger.instance;\n }\n\n private ensureLogDirectory(): void {\n if (!this.logFile) return;\n const logDir = path.dirname(this.logFile);\n try {\n if (!fs.existsSync(logDir)) {\n fs.mkdirSync(logDir, { recursive: true });\n }\n } catch (err: unknown) {\n // Disable file logging if we cannot create the directory (e.g., ENOSPC)\n this.logFile = undefined;\n if (!this.fileLoggingDisabledNotified) {\n this.fileLoggingDisabledNotified = true;\n // Emit a single warning to console so we don't spam output\n const msg =\n '[Logger] File logging disabled (failed to create log directory). Falling back to console only.';\n // Use console directly to avoid recursion\n // eslint-disable-next-line no-console\n console.warn(msg);\n }\n }\n }\n\n private writeLog(entry: LogEntry): void {\n const logLine = JSON.stringify(entry) + '\\n';\n\n // Always write to file if configured\n if (this.logFile) {\n try {\n fs.appendFileSync(this.logFile, logLine);\n } catch (err: unknown) {\n // Disable file logging on error (e.g., ENOSPC) to avoid repeated failures\n this.logFile = undefined;\n if (!this.fileLoggingDisabledNotified) {\n this.fileLoggingDisabledNotified = true;\n const msg =\n '[Logger] File logging disabled (write failed). Falling back to console only.';\n // eslint-disable-next-line no-console\n console.warn(msg);\n }\n }\n }\n\n // Console output based on level\n if (entry.level <= this.logLevel) {\n const levelNames = ['ERROR', 'WARN', 'INFO', 'DEBUG'];\n const levelName = levelNames[entry.level] || 'UNKNOWN';\n\n const consoleMessage = `[${entry.timestamp}] ${levelName}: ${entry.message}`;\n\n if (entry.level === LogLevel.ERROR) {\n console.error(consoleMessage);\n if (entry.error) {\n console.error(entry.error.stack);\n }\n } else if (entry.level === LogLevel.WARN) {\n console.warn(consoleMessage);\n } else {\n console.log(consoleMessage);\n }\n }\n }\n\n error(\n message: string,\n errorOrContext?: Error | Record<string, unknown>,\n context?: Record<string, unknown>\n ): void {\n const isError = errorOrContext instanceof Error;\n this.writeLog({\n timestamp: new Date().toISOString(),\n level: LogLevel.ERROR,\n message,\n context: isError ? context : (errorOrContext as Record<string, unknown>),\n error: isError ? errorOrContext : undefined,\n });\n }\n\n warn(\n message: string,\n errorOrContext?: Error | Record<string, unknown>\n ): void {\n const isError = errorOrContext instanceof Error;\n this.writeLog({\n timestamp: new Date().toISOString(),\n level: LogLevel.WARN,\n message,\n context: isError\n ? undefined\n : (errorOrContext as Record<string, unknown>),\n error: isError ? errorOrContext : undefined,\n });\n }\n\n info(message: string, context?: Record<string, unknown>): void {\n this.writeLog({\n timestamp: new Date().toISOString(),\n level: LogLevel.INFO,\n message,\n context,\n });\n }\n\n debug(message: string, context?: Record<string, unknown>): void {\n this.writeLog({\n timestamp: new Date().toISOString(),\n level: LogLevel.DEBUG,\n message,\n context,\n });\n }\n}\n\n// Export singleton instance\nexport const logger = Logger.getInstance();\n"],
|
|
5
|
+
"mappings": "AAIA,YAAY,QAAQ;AACpB,YAAY,UAAU;AAEtB,SAAS,OAAO,KAAa,cAA+B;AAC1D,QAAM,QAAQ,QAAQ,IAAI,GAAG;AAC7B,MAAI,UAAU,QAAW;AACvB,QAAI,iBAAiB,OAAW,QAAO;AACvC,UAAM,IAAI,MAAM,wBAAwB,GAAG,cAAc;AAAA,EAC3D;AACA,SAAO;AACT;AAEA,SAAS,eAAe,KAAiC;AACvD,SAAO,QAAQ,IAAI,GAAG;AACxB;AAGO,IAAK,WAAL,kBAAKA,cAAL;AACL,EAAAA,oBAAA,WAAQ,KAAR;AACA,EAAAA,oBAAA,UAAO,KAAP;AACA,EAAAA,oBAAA,UAAO,KAAP;AACA,EAAAA,oBAAA,WAAQ,KAAR;AAJU,SAAAA;AAAA,GAAA;AAeL,MAAM,OAAO;AAAA,EAClB,OAAe;AAAA,EACP,WAAqB;AAAA,EACrB;AAAA,EACA,8BAA8B;AAAA,EAE9B,cAAc;AAEpB,UAAM,WAAW,QAAQ,IAAI,uBAAuB,GAAG,YAAY;AACnE,YAAQ,UAAU;AAAA,MAChB,KAAK;AACH,aAAK,WAAW;AAChB;AAAA,MACF,KAAK;AACH,aAAK,WAAW;AAChB;AAAA,MACF,KAAK;AACH,aAAK,WAAW;AAChB;AAAA,MACF;AACE,aAAK,WAA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fs from "fs";
|
|
3
3
|
import * as path from "path";
|
|
4
4
|
import { logger } from "./logger.js";
|
|
5
|
+
function getEnv(key, defaultValue) {
|
|
6
|
+
const value = process.env[key];
|
|
7
|
+
if (value === void 0) {
|
|
8
|
+
if (defaultValue !== void 0) return defaultValue;
|
|
9
|
+
throw new Error(`Environment variable ${key} is required`);
|
|
10
|
+
}
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
function getOptionalEnv(key) {
|
|
14
|
+
return process.env[key];
|
|
15
|
+
}
|
|
5
16
|
class MetricsCollector extends EventEmitter {
|
|
6
17
|
metrics = [];
|
|
7
18
|
metricsFile;
|
|
@@ -9,9 +20,9 @@ class MetricsCollector extends EventEmitter {
|
|
|
9
20
|
aggregates = /* @__PURE__ */ new Map();
|
|
10
21
|
constructor() {
|
|
11
22
|
super();
|
|
12
|
-
if (process.env
|
|
23
|
+
if (process.env["STACKMEMORY_METRICS_ENABLED"] === "true") {
|
|
13
24
|
const metricsDir = path.join(
|
|
14
|
-
process.env
|
|
25
|
+
process.env["HOME"] || ".",
|
|
15
26
|
".stackmemory",
|
|
16
27
|
"metrics"
|
|
17
28
|
);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/core/monitoring/metrics.ts"],
|
|
4
|
-
"sourcesContent": ["import { EventEmitter } from 'events';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { logger } from './logger.js';\n\ninterface MetricEntry {\n timestamp: Date;\n metric: string;\n value: number;\n type: 'counter' | 'gauge' | 'timing';\n tags?: Record<string, string>;\n}\n\nclass MetricsCollector extends EventEmitter {\n private metrics: MetricEntry[] = [];\n private metricsFile?: string;\n private flushInterval: NodeJS.Timeout | null = null;\n private aggregates: Map<\n string,\n { sum: number; count: number; min: number; max: number }\n > = new Map();\n\n constructor() {\n super();\n\n // Set up metrics file if enabled\n if (process.env
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAAS,cAAc;
|
|
4
|
+
"sourcesContent": ["import { EventEmitter } from 'events';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { logger } from './logger.js';\n// Type-safe environment variable access\nfunction getEnv(key: string, defaultValue?: string): string {\n const value = process.env[key];\n if (value === undefined) {\n if (defaultValue !== undefined) return defaultValue;\n throw new Error(`Environment variable ${key} is required`);\n }\n return value;\n}\n\nfunction getOptionalEnv(key: string): string | undefined {\n return process.env[key];\n}\n\n\ninterface MetricEntry {\n timestamp: Date;\n metric: string;\n value: number;\n type: 'counter' | 'gauge' | 'timing';\n tags?: Record<string, string>;\n}\n\nclass MetricsCollector extends EventEmitter {\n private metrics: MetricEntry[] = [];\n private metricsFile?: string;\n private flushInterval: NodeJS.Timeout | null = null;\n private aggregates: Map<\n string,\n { sum: number; count: number; min: number; max: number }\n > = new Map();\n\n constructor() {\n super();\n\n // Set up metrics file if enabled\n if (process.env['STACKMEMORY_METRICS_ENABLED'] === 'true') {\n const metricsDir = path.join(\n process.env['HOME'] || '.',\n '.stackmemory',\n 'metrics'\n );\n if (!fs.existsSync(metricsDir)) {\n fs.mkdirSync(metricsDir, { recursive: true });\n }\n this.metricsFile = path.join(\n metricsDir,\n `metrics-${new Date().toISOString().split('T')[0]}.jsonl`\n );\n\n // Flush metrics every 30 seconds\n this.flushInterval = setInterval(() => this.flush(), 30000);\n }\n }\n\n async record(\n metric: string,\n value: number,\n tags?: Record<string, string>\n ): Promise<void> {\n const entry: MetricEntry = {\n timestamp: new Date(),\n metric,\n value,\n type: 'gauge',\n tags,\n };\n\n this.metrics.push(entry);\n this.updateAggregates(metric, value);\n this.emit('metric', entry);\n\n // Auto-flush if buffer is large\n if (this.metrics.length > 1000) {\n await this.flush();\n }\n }\n\n async increment(\n metric: string,\n tags?: Record<string, string>,\n value = 1\n ): Promise<void> {\n const entry: MetricEntry = {\n timestamp: new Date(),\n metric,\n value,\n type: 'counter',\n tags,\n };\n\n this.metrics.push(entry);\n this.updateAggregates(metric, value);\n this.emit('metric', entry);\n }\n\n async timing(\n metric: string,\n duration: number,\n tags?: Record<string, string>\n ): Promise<void> {\n const entry: MetricEntry = {\n timestamp: new Date(),\n metric,\n value: duration,\n type: 'timing',\n tags,\n };\n\n this.metrics.push(entry);\n this.updateAggregates(metric, duration);\n this.emit('metric', entry);\n }\n\n private updateAggregates(metric: string, value: number): void {\n const existing = this.aggregates.get(metric) || {\n sum: 0,\n count: 0,\n min: Infinity,\n max: -Infinity,\n };\n\n this.aggregates.set(metric, {\n sum: existing.sum + value,\n count: existing.count + 1,\n min: Math.min(existing.min, value),\n max: Math.max(existing.max, value),\n });\n }\n\n async flush(): Promise<void> {\n if (this.metrics.length === 0) return;\n\n const toFlush = [...this.metrics];\n this.metrics = [];\n\n if (this.metricsFile) {\n try {\n const lines = toFlush.map((m) => JSON.stringify(m)).join('\\n') + '\\n';\n await fs.promises.appendFile(this.metricsFile, lines);\n } catch (error: unknown) {\n logger.error(\n 'Failed to write metrics',\n error instanceof Error ? error : new Error(String(error))\n );\n }\n }\n\n // Emit batch event for external processors\n this.emit('flush', toFlush);\n }\n\n getStats(metric?: string): Record<string, any> {\n if (metric) {\n const stats = this.aggregates.get(metric);\n if (!stats) return {};\n\n return {\n [metric]: {\n ...stats,\n avg: stats.count > 0 ? stats.sum / stats.count : 0,\n },\n };\n }\n\n const result: Record<string, any> = {};\n for (const [key, stats] of this.aggregates.entries()) {\n result[key] = {\n ...stats,\n avg: stats.count > 0 ? stats.sum / stats.count : 0,\n };\n }\n return result;\n }\n\n reset(): void {\n this.metrics = [];\n this.aggregates.clear();\n }\n\n destroy(): void {\n if (this.flushInterval) {\n clearInterval(this.flushInterval);\n this.flushInterval = null;\n }\n this.flush();\n }\n}\n\n// Singleton instance\nconst collector = new MetricsCollector();\n\n// Cleanup on exit\nprocess.on('beforeExit', () => collector.destroy());\n\nexport class Metrics {\n static async record(\n metric: string,\n value: number,\n tags?: Record<string, string>\n ): Promise<void> {\n await collector.record(metric, value, tags);\n }\n\n static async increment(\n metric: string,\n tags?: Record<string, string>\n ): Promise<void> {\n await collector.increment(metric, tags);\n }\n\n static async timing(\n metric: string,\n duration: number,\n tags?: Record<string, string>\n ): Promise<void> {\n await collector.timing(metric, duration, tags);\n }\n\n static getStats(metric?: string): Record<string, any> {\n return collector.getStats(metric);\n }\n\n static reset(): void {\n collector.reset();\n }\n\n static on(event: string, listener: (...args: any[]) => void): void {\n collector.on(event, listener);\n }\n}\n\nexport const metrics = Metrics;\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAAS,cAAc;AAEvB,SAAS,OAAO,KAAa,cAA+B;AAC1D,QAAM,QAAQ,QAAQ,IAAI,GAAG;AAC7B,MAAI,UAAU,QAAW;AACvB,QAAI,iBAAiB,OAAW,QAAO;AACvC,UAAM,IAAI,MAAM,wBAAwB,GAAG,cAAc;AAAA,EAC3D;AACA,SAAO;AACT;AAEA,SAAS,eAAe,KAAiC;AACvD,SAAO,QAAQ,IAAI,GAAG;AACxB;AAWA,MAAM,yBAAyB,aAAa;AAAA,EAClC,UAAyB,CAAC;AAAA,EAC1B;AAAA,EACA,gBAAuC;AAAA,EACvC,aAGJ,oBAAI,IAAI;AAAA,EAEZ,cAAc;AACZ,UAAM;AAGN,QAAI,QAAQ,IAAI,6BAA6B,MAAM,QAAQ;AACzD,YAAM,aAAa,KAAK;AAAA,QACtB,QAAQ,IAAI,MAAM,KAAK;AAAA,QACvB;AAAA,QACA;AAAA,MACF;AACA,UAAI,CAAC,GAAG,WAAW,UAAU,GAAG;AAC9B,WAAG,UAAU,YAAY,EAAE,WAAW,KAAK,CAAC;AAAA,MAC9C;AACA,WAAK,cAAc,KAAK;AAAA,QACtB;AAAA,QACA,YAAW,oBAAI,KAAK,GAAE,YAAY,EAAE,MAAM,GAAG,EAAE,CAAC,CAAC;AAAA,MACnD;AAG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c,KAAK,aAAa;AAChC,WAAK,gBAAgB;AAAA,IACvB;AACA,SAAK,MAAM;AAAA,EACb;AACF;AAGA,MAAM,YAAY,IAAI,iBAAiB;AAGvC,QAAQ,GAAG,cAAc,MAAM,UAAU,QAAQ,CAAC;AAE3C,MAAM,QAAQ;AAAA,EACnB,aAAa,OACX,QACA,OACA,MACe;AACf,UAAM,UAAU,OAAO,QAAQ,OAAO,IAAI;AAAA,EAC5C;AAAA,EAEA,aAAa,UACX,QACA,MACe;AACf,UAAM,UAAU,UAAU,QAAQ,IAAI;AAAA,EACxC;AAAA,EAEA,aAAa,OACX,QACA,UACA,MACe;AACf,UAAM,UAAU,OAAO,QAAQ,UAAU,IAAI;AAAA,EAC/C;AAAA,EAEA,OAAO,SAAS,QAAsC;AACpD,WAAO,UAAU,SAAS,MAAM;AAAA,EAClC;AAAA,EAEA,OAAO,QAAc;AACnB,cAAU,MAAM;AAAA,EAClB;AAAA,EAEA,OAAO,GAAG,OAAe,UAA0C;AACjE,cAAU,GAAG,OAAO,QAAQ;AAAA,EAC9B;AACF;AAEO,MAAM,UAAU;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
2
2
|
import { join } from "path";
|
|
3
|
+
function getEnv(key, defaultValue) {
|
|
4
|
+
const value = process.env[key];
|
|
5
|
+
if (value === void 0) {
|
|
6
|
+
if (defaultValue !== void 0) return defaultValue;
|
|
7
|
+
throw new Error(`Environment variable ${key} is required`);
|
|
8
|
+
}
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
function getOptionalEnv(key) {
|
|
12
|
+
return process.env[key];
|
|
13
|
+
}
|
|
3
14
|
class ProgressTracker {
|
|
4
15
|
progressFile;
|
|
5
16
|
data;
|
|
@@ -19,7 +30,7 @@ class ProgressTracker {
|
|
|
19
30
|
}
|
|
20
31
|
}
|
|
21
32
|
return {
|
|
22
|
-
version: process.env
|
|
33
|
+
version: process.env["npm_package_version"] || "0.2.3",
|
|
23
34
|
lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
|
|
24
35
|
recentChanges: []
|
|
25
36
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/core/monitoring/progress-tracker.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Progress Tracker for StackMemory\n * Maintains a JSON file with recent changes and progress\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport interface TaskProgress {\n task: string;\n completedAt?: string;\n startedAt?: string;\n status: 'completed' | 'in_progress' | 'pending';\n changes?: string[];\n}\n\nexport interface Change {\n date: string;\n version: string;\n type: 'feature' | 'bugfix' | 'refactor' | 'docs';\n description: string;\n files?: string[];\n}\n\nexport interface ProgressData {\n version: string;\n lastUpdated: string;\n currentSession?: {\n startTime: string;\n tasksCompleted: TaskProgress[];\n inProgress: string[];\n };\n recentChanges: Change[];\n linearIntegration?: {\n status: string;\n lastSync?: string;\n tasksSynced?: number;\n issues?: string[];\n };\n roadmap?: {\n immediate: string[];\n thisWeek: string[];\n nextSprint: string[];\n };\n metrics?: Record<string, any>;\n notes?: string[];\n}\n\nexport class ProgressTracker {\n private progressFile: string;\n private data: ProgressData;\n\n constructor(projectRoot: string) {\n this.progressFile = join(projectRoot, '.stackmemory', 'progress.json');\n this.data = this.load();\n }\n\n /**\n * Load progress data from file\n */\n private load(): ProgressData {\n if (existsSync(this.progressFile)) {\n try {\n const content = readFileSync(this.progressFile, 'utf-8');\n return JSON.parse(content);\n } catch {\n // Start with empty data if file is corrupted\n }\n }\n\n // Default structure\n return {\n version: process.env
|
|
5
|
-
"mappings": "AAKA,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,YAAY;
|
|
4
|
+
"sourcesContent": ["/**\n * Progress Tracker for StackMemory\n * Maintains a JSON file with recent changes and progress\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'fs';\nimport { join } from 'path';\n// Type-safe environment variable access\nfunction getEnv(key: string, defaultValue?: string): string {\n const value = process.env[key];\n if (value === undefined) {\n if (defaultValue !== undefined) return defaultValue;\n throw new Error(`Environment variable ${key} is required`);\n }\n return value;\n}\n\nfunction getOptionalEnv(key: string): string | undefined {\n return process.env[key];\n}\n\n\nexport interface TaskProgress {\n task: string;\n completedAt?: string;\n startedAt?: string;\n status: 'completed' | 'in_progress' | 'pending';\n changes?: string[];\n}\n\nexport interface Change {\n date: string;\n version: string;\n type: 'feature' | 'bugfix' | 'refactor' | 'docs';\n description: string;\n files?: string[];\n}\n\nexport interface ProgressData {\n version: string;\n lastUpdated: string;\n currentSession?: {\n startTime: string;\n tasksCompleted: TaskProgress[];\n inProgress: string[];\n };\n recentChanges: Change[];\n linearIntegration?: {\n status: string;\n lastSync?: string;\n tasksSynced?: number;\n issues?: string[];\n };\n roadmap?: {\n immediate: string[];\n thisWeek: string[];\n nextSprint: string[];\n };\n metrics?: Record<string, any>;\n notes?: string[];\n}\n\nexport class ProgressTracker {\n private progressFile: string;\n private data: ProgressData;\n\n constructor(projectRoot: string) {\n this.progressFile = join(projectRoot, '.stackmemory', 'progress.json');\n this.data = this.load();\n }\n\n /**\n * Load progress data from file\n */\n private load(): ProgressData {\n if (existsSync(this.progressFile)) {\n try {\n const content = readFileSync(this.progressFile, 'utf-8');\n return JSON.parse(content);\n } catch {\n // Start with empty data if file is corrupted\n }\n }\n\n // Default structure\n return {\n version: process.env['npm_package_version'] || '0.2.3',\n lastUpdated: new Date().toISOString(),\n recentChanges: [],\n };\n }\n\n /**\n * Save progress data to file\n */\n private save(): void {\n this.data.lastUpdated = new Date().toISOString();\n writeFileSync(this.progressFile, JSON.stringify(this.data, null, 2));\n }\n\n /**\n * Start a new session\n */\n startSession(): void {\n this.data.currentSession = {\n startTime: new Date().toISOString(),\n tasksCompleted: [],\n inProgress: [],\n };\n this.save();\n }\n\n /**\n * Add a task as in progress\n */\n startTask(task: string): void {\n if (!this.data.currentSession) {\n this.startSession();\n }\n\n if (this.data.currentSession!.inProgress.indexOf(task) === -1) {\n this.data.currentSession!.inProgress.push(task);\n }\n this.save();\n }\n\n /**\n * Mark a task as completed\n */\n completeTask(task: string, changes?: string[]): void {\n if (!this.data.currentSession) {\n this.startSession();\n }\n\n // Remove from in progress\n const index = this.data.currentSession!.inProgress.indexOf(task);\n if (index > -1) {\n this.data.currentSession!.inProgress.splice(index, 1);\n }\n\n // Add to completed\n this.data.currentSession!.tasksCompleted.push({\n task,\n completedAt: new Date().toISOString(),\n status: 'completed',\n changes,\n });\n\n this.save();\n }\n\n /**\n * Add a recent change\n */\n addChange(change: Change): void {\n // Keep only last 20 changes\n this.data.recentChanges.unshift(change);\n if (this.data.recentChanges.length > 20) {\n this.data.recentChanges = this.data.recentChanges.slice(0, 20);\n }\n this.save();\n }\n\n /**\n * Update Linear integration status\n */\n updateLinearStatus(status: {\n lastSync?: string;\n tasksSynced?: number;\n issues?: string[];\n }): void {\n if (!this.data.linearIntegration) {\n this.data.linearIntegration = {\n status: 'active',\n };\n }\n\n Object.assign(this.data.linearIntegration, status);\n this.save();\n }\n\n /**\n * Add a note\n */\n addNote(note: string): void {\n if (!this.data.notes) {\n this.data.notes = [];\n }\n\n // Add to beginning and keep last 10\n this.data.notes.unshift(note);\n if (this.data.notes.length > 10) {\n this.data.notes = this.data.notes.slice(0, 10);\n }\n this.save();\n }\n\n /**\n * Get current progress\n */\n getProgress(): ProgressData {\n return this.data;\n }\n\n /**\n * Get summary for display\n */\n getSummary(): string {\n const lines: string[] = [];\n\n lines.push(`\uD83D\uDCCA StackMemory Progress (v${this.data.version})`);\n lines.push(`Last updated: ${this.data.lastUpdated}`);\n\n if (this.data.currentSession) {\n lines.push('\\n\uD83D\uDCCD Current Session:');\n lines.push(` Started: ${this.data.currentSession.startTime}`);\n lines.push(\n ` Completed: ${this.data.currentSession.tasksCompleted.length} tasks`\n );\n\n if (this.data.currentSession.inProgress.length > 0) {\n lines.push(` In Progress:`);\n this.data.currentSession.inProgress.forEach((task) => {\n lines.push(` - ${task}`);\n });\n }\n }\n\n if (this.data.recentChanges.length > 0) {\n lines.push('\\n\uD83D\uDD04 Recent Changes:');\n this.data.recentChanges.slice(0, 5).forEach((change) => {\n lines.push(` [${change.date}] ${change.type}: ${change.description}`);\n });\n }\n\n if (this.data.linearIntegration) {\n lines.push('\\n\uD83D\uDD17 Linear Integration:');\n lines.push(` Status: ${this.data.linearIntegration.status}`);\n if (this.data.linearIntegration.lastSync) {\n lines.push(` Last sync: ${this.data.linearIntegration.lastSync}`);\n }\n if (this.data.linearIntegration.tasksSynced) {\n lines.push(\n ` Tasks synced: ${this.data.linearIntegration.tasksSynced}`\n );\n }\n }\n\n if (this.data.notes && this.data.notes.length > 0) {\n lines.push('\\n\uD83D\uDCDD Recent Notes:');\n this.data.notes.slice(0, 3).forEach((note) => {\n lines.push(` \u2022 ${note}`);\n });\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Clear current session\n */\n endSession(): void {\n delete this.data.currentSession;\n this.save();\n }\n}\n"],
|
|
5
|
+
"mappings": "AAKA,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,YAAY;AAErB,SAAS,OAAO,KAAa,cAA+B;AAC1D,QAAM,QAAQ,QAAQ,IAAI,GAAG;AAC7B,MAAI,UAAU,QAAW;AACvB,QAAI,iBAAiB,OAAW,QAAO;AACvC,UAAM,IAAI,MAAM,wBAAwB,GAAG,cAAc;AAAA,EAC3D;AACA,SAAO;AACT;AAEA,SAAS,eAAe,KAAiC;AACvD,SAAO,QAAQ,IAAI,GAAG;AACxB;AA2CO,MAAM,gBAAgB;AAAA,EACnB;AAAA,EACA;AAAA,EAER,YAAY,aAAqB;AAC/B,SAAK,eAAe,KAAK,aAAa,gBAAgB,eAAe;AACrE,SAAK,OAAO,KAAK,KAAK;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA,EAKQ,OAAqB;AAC3B,QAAI,WAA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AA,EACZ;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/core/monitoring/session-monitor.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Session Monitor for StackMemory\n * Automatically triggers features based on session events\n */\n\nimport { EventEmitter } from 'events';\nimport { ClearSurvival } from '../session/clear-survival.js';\nimport { HandoffGenerator } from '../session/handoff-generator.js';\nimport { FrameManager } from '../frame/frame-manager.js';\nimport { DatabaseManager } from '../storage/database-manager.js';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\n\nexport interface MonitorConfig {\n // Context thresholds\n contextWarningThreshold: number; // Default 0.6 (60%)\n contextCriticalThreshold: number; // Default 0.7 (70%)\n contextAutoSaveThreshold: number; // Default 0.85 (85%)\n\n // Handoff triggers\n idleTimeoutMinutes: number; // Default 5 minutes\n sessionEndHandoff: boolean; // Default true\n\n // Monitoring intervals\n checkIntervalSeconds: number; // Default 30 seconds\n\n // Auto actions\n autoSaveLedger: boolean; // Default true\n autoGenerateHandoff: boolean; // Default true\n autoCompactOnThreshold: boolean; // Default false\n}\n\nexport class SessionMonitor extends EventEmitter {\n private config: MonitorConfig;\n private clearSurvival: ClearSurvival;\n private handoffGenerator: HandoffGenerator;\n private frameManager: FrameManager;\n private dbManager: DatabaseManager;\n private monitorInterval?: NodeJS.Timeout;\n private lastActivityTime: Date;\n private isMonitoring: boolean = false;\n private projectRoot: string;\n\n // Track context state to avoid duplicate saves\n private lastContextCheck: {\n tokens: number;\n percentage: number;\n savedAt?: Date;\n } = { tokens: 0, percentage: 0 };\n\n constructor(\n frameManager: FrameManager,\n dbManager: DatabaseManager,\n projectRoot: string,\n config?: Partial<MonitorConfig>\n ) {\n super();\n\n this.frameManager = frameManager;\n this.dbManager = dbManager;\n this.projectRoot = projectRoot;\n this.lastActivityTime = new Date();\n\n // Initialize config with defaults\n this.config = {\n contextWarningThreshold: 0.6,\n contextCriticalThreshold: 0.7,\n contextAutoSaveThreshold: 0.85,\n idleTimeoutMinutes: 5,\n sessionEndHandoff: true,\n checkIntervalSeconds: 30,\n autoSaveLedger: true,\n autoGenerateHandoff: true,\n autoCompactOnThreshold: false,\n ...config,\n };\n\n // Initialize components\n this.clearSurvival = new ClearSurvival(\n frameManager,\n dbManager,\n new HandoffGenerator(frameManager, dbManager, projectRoot),\n projectRoot\n );\n\n this.handoffGenerator = new HandoffGenerator(\n frameManager,\n dbManager,\n projectRoot\n );\n }\n\n /**\n * Start monitoring session\n */\n async start(): Promise<void> {\n if (this.isMonitoring) return;\n\n this.isMonitoring = true;\n this.lastActivityTime = new Date();\n\n // Start monitoring loop\n this.monitorInterval = setInterval(\n () => this.checkSession(),\n this.config.checkIntervalSeconds * 1000\n );\n\n // Register exit handlers\n this.registerExitHandlers();\n\n this.emit('monitor:started');\n console.log('\uD83D\uDD0D Session monitor started');\n }\n\n /**\n * Stop monitoring\n */\n async stop(): Promise<void> {\n if (!this.isMonitoring) return;\n\n this.isMonitoring = false;\n\n if (this.monitorInterval) {\n clearInterval(this.monitorInterval);\n this.monitorInterval = undefined;\n }\n\n // Generate final handoff if configured\n if (this.config.sessionEndHandoff) {\n await this.generateHandoff('session_end');\n }\n\n this.emit('monitor:stopped');\n console.log('\uD83D\uDED1 Session monitor stopped');\n }\n\n /**\n * Main monitoring check\n */\n private async checkSession(): Promise<void> {\n try {\n // Check context usage\n await this.checkContextUsage();\n\n // Check for idle timeout\n await this.checkIdleTimeout();\n\n // Check for other triggers\n await this.checkCustomTriggers();\n } catch (error) {\n console.error('Monitor check failed:', error);\n this.emit('monitor:error', error);\n }\n }\n\n /**\n * Check context usage and trigger actions\n */\n private async checkContextUsage(): Promise<void> {\n const currentTokens = await this.estimateTokens();\n const maxTokens = 100000; // Claude's approximate limit\n const percentage = currentTokens / maxTokens;\n\n // Store for comparison\n this.lastContextCheck = {\n tokens: currentTokens,\n percentage,\n savedAt: this.lastContextCheck.savedAt,\n };\n\n // Emit usage update\n this.emit('context:usage', {\n tokens: currentTokens,\n maxTokens,\n percentage,\n status: this.getContextStatus(percentage),\n });\n\n // Check thresholds and take action\n if (percentage >= this.config.contextAutoSaveThreshold) {\n await this.handleCriticalContext();\n } else if (percentage >= this.config.contextCriticalThreshold) {\n await this.handleHighContext();\n } else if (percentage >= this.config.contextWarningThreshold) {\n this.handleWarningContext();\n }\n }\n\n /**\n * Handle critical context (>85%)\n */\n private async handleCriticalContext(): Promise<void> {\n // Avoid duplicate saves within 5 minutes\n if (this.lastContextCheck.savedAt) {\n const minsSinceLastSave =\n (Date.now() - this.lastContextCheck.savedAt.getTime()) / 60000;\n if (minsSinceLastSave < 5) return;\n }\n\n console.log('\uD83D\uDD34 Critical context usage - auto-saving ledger');\n\n if (this.config.autoSaveLedger) {\n const ledger = await this.clearSurvival.saveContinuityLedger();\n this.lastContextCheck.savedAt = new Date();\n\n this.emit('context:ledger_saved', {\n compression: ledger.compression_ratio,\n frames: ledger.active_frame_stack.length,\n tasks: ledger.active_tasks.length,\n });\n\n // Suggest clear\n console.log('\uD83D\uDCA1 Ledger saved. Run /clear to reset context');\n\n if (this.config.autoCompactOnThreshold) {\n // This would trigger actual compaction\n // For now, just emit event for external handling\n this.emit('context:suggest_clear');\n }\n }\n }\n\n /**\n * Handle high context (70-85%)\n */\n private async handleHighContext(): Promise<void> {\n console.log('\u26A0\uFE0F High context usage - consider saving ledger');\n\n this.emit('context:high', {\n percentage: this.lastContextCheck.percentage,\n suggestion: 'Run: stackmemory clear --save',\n });\n }\n\n /**\n * Handle warning context (60-70%)\n */\n private handleWarningContext(): void {\n this.emit('context:warning', {\n percentage: this.lastContextCheck.percentage,\n });\n }\n\n /**\n * Check for idle timeout\n */\n private async checkIdleTimeout(): Promise<void> {\n const idleMinutes = (Date.now() - this.lastActivityTime.getTime()) / 60000;\n\n if (idleMinutes >= this.config.idleTimeoutMinutes) {\n if (this.config.autoGenerateHandoff) {\n await this.generateHandoff('idle_timeout');\n }\n }\n }\n\n /**\n * Generate handoff document\n */\n private async generateHandoff(trigger: string): Promise<void> {\n try {\n const sessionId = await this.dbManager.getCurrentSessionId();\n const handoff = await this.handoffGenerator.generateHandoff(sessionId);\n\n this.emit('handoff:generated', {\n trigger,\n sessionDuration: handoff.session_duration_minutes,\n tasksActive: handoff.active_tasks.filter(\n (t) => t.status !== 'completed'\n ).length,\n });\n\n console.log(`\uD83D\uDCCB Handoff generated (trigger: ${trigger})`);\n } catch (error) {\n console.error('Failed to generate handoff:', error);\n }\n }\n\n /**\n * Register process exit handlers\n */\n private registerExitHandlers(): void {\n const exitHandler = async (signal: string) => {\n console.log(`\\n\uD83D\uDCE6 Received ${signal}, saving session state...`);\n\n try {\n // Save ledger if context is significant\n if (this.lastContextCheck.percentage > 0.3) {\n await this.clearSurvival.saveContinuityLedger();\n console.log('\u2705 Continuity ledger saved');\n }\n\n // Generate handoff\n if (this.config.sessionEndHandoff) {\n await this.generateHandoff('process_exit');\n console.log('\u2705 Handoff document generated');\n }\n } catch (error) {\n console.error('Error during exit handling:', error);\n } finally {\n process.exit(0);\n }\n };\n\n // Handle various exit signals\n process.once('SIGINT', () => exitHandler('SIGINT'));\n process.once('SIGTERM', () => exitHandler('SIGTERM'));\n process.once('beforeExit', () => exitHandler('beforeExit'));\n }\n\n /**\n * Update last activity time\n */\n updateActivity(): void {\n this.lastActivityTime = new Date();\n }\n\n /**\n * Check custom triggers (extensible)\n */\n private async checkCustomTriggers(): Promise<void> {\n // Load custom triggers from hooks directory\n const hooksDir = path.join(this.projectRoot, '.stackmemory', 'hooks');\n\n try {\n await fs.access(hooksDir);\n const hooks = await fs.readdir(hooksDir);\n\n for (const hook of hooks) {\n if (hook.startsWith('monitor_') && hook.endsWith('.js')) {\n try {\n const hookPath = path.join(hooksDir, hook);\n const hookModule = await import(hookPath);\n\n if (hookModule.check) {\n const shouldTrigger = await hookModule.check({\n contextPercentage: this.lastContextCheck.percentage,\n idleMinutes:\n (Date.now() - this.lastActivityTime.getTime()) / 60000,\n frameCount: (await this.frameManager.getStack()).frames.length,\n });\n\n if (shouldTrigger && hookModule.action) {\n await hookModule.action({\n clearSurvival: this.clearSurvival,\n handoffGenerator: this.handoffGenerator,\n frameManager: this.frameManager,\n });\n }\n }\n } catch (error) {\n console.error(`Hook ${hook} failed:`, error);\n }\n }\n }\n } catch {\n // No hooks directory\n }\n }\n\n /**\n * Estimate current token usage\n */\n private async estimateTokens(): Promise<number> {\n const sessionId = await this.dbManager.getCurrentSessionId();\n const frames = await this.dbManager.getRecentFrames(sessionId, 100);\n const traces = await this.dbManager.getRecentTraces(sessionId, 100);\n\n // Rough estimation\n return frames.length * 200 + traces.length * 100;\n }\n\n /**\n * Get context status based on percentage\n */\n private getContextStatus(percentage: number): string {\n if (percentage >= this.config.contextAutoSaveThreshold) return 'critical';\n if (percentage >= this.config.contextCriticalThreshold) return 'high';\n if (percentage >= this.config.contextWarningThreshold) return 'warning';\n return 'ok';\n }\n\n /**\n * Get current monitor status\n */\n getStatus(): {\n isMonitoring: boolean;\n lastActivity: Date;\n contextUsage: typeof this.lastContextCheck;\n config: MonitorConfig;\n } {\n return {\n isMonitoring: this.isMonitoring,\n lastActivity: this.lastActivityTime,\n contextUsage: this.lastContextCheck,\n config: this.config,\n };\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<MonitorConfig>): void {\n this.config = { ...this.config, ...config };\n this.emit('config:updated', this.config);\n }\n}\n"],
|
|
5
|
-
"mappings": "AAKA,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,wBAAwB;AAGjC,YAAY,QAAQ;AACpB,YAAY,UAAU;AAqBf,MAAM,uBAAuB,aAAa;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAAwB;AAAA,EACxB;AAAA;AAAA,EAGA,mBAIJ,EAAE,QAAQ,GAAG,YAAY,EAAE;AAAA,EAE/B,YAC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C1C,QAAI;AAEF,YAAM,KAAK,kBAAkB;AAG7B,YAAM,KAAK,iBAAiB;AAG5B,YAAM,KAAK,oBAAoB;AAAA,IACjC,SAAS,
|
|
4
|
+
"sourcesContent": ["/**\n * Session Monitor for StackMemory\n * Automatically triggers features based on session events\n */\n\nimport { EventEmitter } from 'events';\nimport { ClearSurvival } from '../session/clear-survival.js';\nimport { HandoffGenerator } from '../session/handoff-generator.js';\nimport { FrameManager } from '../frame/frame-manager.js';\nimport { DatabaseManager } from '../storage/database-manager.js';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\n\nexport interface MonitorConfig {\n // Context thresholds\n contextWarningThreshold: number; // Default 0.6 (60%)\n contextCriticalThreshold: number; // Default 0.7 (70%)\n contextAutoSaveThreshold: number; // Default 0.85 (85%)\n\n // Handoff triggers\n idleTimeoutMinutes: number; // Default 5 minutes\n sessionEndHandoff: boolean; // Default true\n\n // Monitoring intervals\n checkIntervalSeconds: number; // Default 30 seconds\n\n // Auto actions\n autoSaveLedger: boolean; // Default true\n autoGenerateHandoff: boolean; // Default true\n autoCompactOnThreshold: boolean; // Default false\n}\n\nexport class SessionMonitor extends EventEmitter {\n private config: MonitorConfig;\n private clearSurvival: ClearSurvival;\n private handoffGenerator: HandoffGenerator;\n private frameManager: FrameManager;\n private dbManager: DatabaseManager;\n private monitorInterval?: NodeJS.Timeout;\n private lastActivityTime: Date;\n private isMonitoring: boolean = false;\n private projectRoot: string;\n\n // Track context state to avoid duplicate saves\n private lastContextCheck: {\n tokens: number;\n percentage: number;\n savedAt?: Date;\n } = { tokens: 0, percentage: 0 };\n\n constructor(\n frameManager: FrameManager,\n dbManager: DatabaseManager,\n projectRoot: string,\n config?: Partial<MonitorConfig>\n ) {\n super();\n\n this.frameManager = frameManager;\n this.dbManager = dbManager;\n this.projectRoot = projectRoot;\n this.lastActivityTime = new Date();\n\n // Initialize config with defaults\n this.config = {\n contextWarningThreshold: 0.6,\n contextCriticalThreshold: 0.7,\n contextAutoSaveThreshold: 0.85,\n idleTimeoutMinutes: 5,\n sessionEndHandoff: true,\n checkIntervalSeconds: 30,\n autoSaveLedger: true,\n autoGenerateHandoff: true,\n autoCompactOnThreshold: false,\n ...config,\n };\n\n // Initialize components\n this.clearSurvival = new ClearSurvival(\n frameManager,\n dbManager,\n new HandoffGenerator(frameManager, dbManager, projectRoot),\n projectRoot\n );\n\n this.handoffGenerator = new HandoffGenerator(\n frameManager,\n dbManager,\n projectRoot\n );\n }\n\n /**\n * Start monitoring session\n */\n async start(): Promise<void> {\n if (this.isMonitoring) return;\n\n this.isMonitoring = true;\n this.lastActivityTime = new Date();\n\n // Start monitoring loop\n this.monitorInterval = setInterval(\n () => this.checkSession(),\n this.config.checkIntervalSeconds * 1000\n );\n\n // Register exit handlers\n this.registerExitHandlers();\n\n this.emit('monitor:started');\n console.log('\uD83D\uDD0D Session monitor started');\n }\n\n /**\n * Stop monitoring\n */\n async stop(): Promise<void> {\n if (!this.isMonitoring) return;\n\n this.isMonitoring = false;\n\n if (this.monitorInterval) {\n clearInterval(this.monitorInterval);\n this.monitorInterval = undefined;\n }\n\n // Generate final handoff if configured\n if (this.config.sessionEndHandoff) {\n await this.generateHandoff('session_end');\n }\n\n this.emit('monitor:stopped');\n console.log('\uD83D\uDED1 Session monitor stopped');\n }\n\n /**\n * Main monitoring check\n */\n private async checkSession(): Promise<void> {\n try {\n // Check context usage\n await this.checkContextUsage();\n\n // Check for idle timeout\n await this.checkIdleTimeout();\n\n // Check for other triggers\n await this.checkCustomTriggers();\n } catch (error: unknown) {\n console.error('Monitor check failed:', error);\n this.emit('monitor:error', error);\n }\n }\n\n /**\n * Check context usage and trigger actions\n */\n private async checkContextUsage(): Promise<void> {\n const currentTokens = await this.estimateTokens();\n const maxTokens = 100000; // Claude's approximate limit\n const percentage = currentTokens / maxTokens;\n\n // Store for comparison\n this.lastContextCheck = {\n tokens: currentTokens,\n percentage,\n savedAt: this.lastContextCheck.savedAt,\n };\n\n // Emit usage update\n this.emit('context:usage', {\n tokens: currentTokens,\n maxTokens,\n percentage,\n status: this.getContextStatus(percentage),\n });\n\n // Check thresholds and take action\n if (percentage >= this.config.contextAutoSaveThreshold) {\n await this.handleCriticalContext();\n } else if (percentage >= this.config.contextCriticalThreshold) {\n await this.handleHighContext();\n } else if (percentage >= this.config.contextWarningThreshold) {\n this.handleWarningContext();\n }\n }\n\n /**\n * Handle critical context (>85%)\n */\n private async handleCriticalContext(): Promise<void> {\n // Avoid duplicate saves within 5 minutes\n if (this.lastContextCheck.savedAt) {\n const minsSinceLastSave =\n (Date.now() - this.lastContextCheck.savedAt.getTime()) / 60000;\n if (minsSinceLastSave < 5) return;\n }\n\n console.log('\uD83D\uDD34 Critical context usage - auto-saving ledger');\n\n if (this.config.autoSaveLedger) {\n const ledger = await this.clearSurvival.saveContinuityLedger();\n this.lastContextCheck.savedAt = new Date();\n\n this.emit('context:ledger_saved', {\n compression: ledger.compression_ratio,\n frames: ledger.active_frame_stack.length,\n tasks: ledger.active_tasks.length,\n });\n\n // Suggest clear\n console.log('\uD83D\uDCA1 Ledger saved. Run /clear to reset context');\n\n if (this.config.autoCompactOnThreshold) {\n // This would trigger actual compaction\n // For now, just emit event for external handling\n this.emit('context:suggest_clear');\n }\n }\n }\n\n /**\n * Handle high context (70-85%)\n */\n private async handleHighContext(): Promise<void> {\n console.log('\u26A0\uFE0F High context usage - consider saving ledger');\n\n this.emit('context:high', {\n percentage: this.lastContextCheck.percentage,\n suggestion: 'Run: stackmemory clear --save',\n });\n }\n\n /**\n * Handle warning context (60-70%)\n */\n private handleWarningContext(): void {\n this.emit('context:warning', {\n percentage: this.lastContextCheck.percentage,\n });\n }\n\n /**\n * Check for idle timeout\n */\n private async checkIdleTimeout(): Promise<void> {\n const idleMinutes = (Date.now() - this.lastActivityTime.getTime()) / 60000;\n\n if (idleMinutes >= this.config.idleTimeoutMinutes) {\n if (this.config.autoGenerateHandoff) {\n await this.generateHandoff('idle_timeout');\n }\n }\n }\n\n /**\n * Generate handoff document\n */\n private async generateHandoff(trigger: string): Promise<void> {\n try {\n const sessionId = await this.dbManager.getCurrentSessionId();\n const handoff = await this.handoffGenerator.generateHandoff(sessionId);\n\n this.emit('handoff:generated', {\n trigger,\n sessionDuration: handoff.session_duration_minutes,\n tasksActive: handoff.active_tasks.filter(\n (t) => t.status !== 'completed'\n ).length,\n });\n\n console.log(`\uD83D\uDCCB Handoff generated (trigger: ${trigger})`);\n } catch (error: unknown) {\n console.error('Failed to generate handoff:', error);\n }\n }\n\n /**\n * Register process exit handlers\n */\n private registerExitHandlers(): void {\n const exitHandler = async (signal: string) => {\n console.log(`\\n\uD83D\uDCE6 Received ${signal}, saving session state...`);\n\n try {\n // Save ledger if context is significant\n if (this.lastContextCheck.percentage > 0.3) {\n await this.clearSurvival.saveContinuityLedger();\n console.log('\u2705 Continuity ledger saved');\n }\n\n // Generate handoff\n if (this.config.sessionEndHandoff) {\n await this.generateHandoff('process_exit');\n console.log('\u2705 Handoff document generated');\n }\n } catch (error: unknown) {\n console.error('Error during exit handling:', error);\n } finally {\n process.exit(0);\n }\n };\n\n // Handle various exit signals\n process.once('SIGINT', () => exitHandler('SIGINT'));\n process.once('SIGTERM', () => exitHandler('SIGTERM'));\n process.once('beforeExit', () => exitHandler('beforeExit'));\n }\n\n /**\n * Update last activity time\n */\n updateActivity(): void {\n this.lastActivityTime = new Date();\n }\n\n /**\n * Check custom triggers (extensible)\n */\n private async checkCustomTriggers(): Promise<void> {\n // Load custom triggers from hooks directory\n const hooksDir = path.join(this.projectRoot, '.stackmemory', 'hooks');\n\n try {\n await fs.access(hooksDir);\n const hooks = await fs.readdir(hooksDir);\n\n for (const hook of hooks) {\n if (hook.startsWith('monitor_') && hook.endsWith('.js')) {\n try {\n const hookPath = path.join(hooksDir, hook);\n const hookModule = await import(hookPath);\n\n if (hookModule.check) {\n const shouldTrigger = await hookModule.check({\n contextPercentage: this.lastContextCheck.percentage,\n idleMinutes:\n (Date.now() - this.lastActivityTime.getTime()) / 60000,\n frameCount: (await this.frameManager.getStack()).frames.length,\n });\n\n if (shouldTrigger && hookModule.action) {\n await hookModule.action({\n clearSurvival: this.clearSurvival,\n handoffGenerator: this.handoffGenerator,\n frameManager: this.frameManager,\n });\n }\n }\n } catch (error: unknown) {\n console.error(`Hook ${hook} failed:`, error);\n }\n }\n }\n } catch {\n // No hooks directory\n }\n }\n\n /**\n * Estimate current token usage\n */\n private async estimateTokens(): Promise<number> {\n const sessionId = await this.dbManager.getCurrentSessionId();\n const frames = await this.dbManager.getRecentFrames(sessionId, 100);\n const traces = await this.dbManager.getRecentTraces(sessionId, 100);\n\n // Rough estimation\n return frames.length * 200 + traces.length * 100;\n }\n\n /**\n * Get context status based on percentage\n */\n private getContextStatus(percentage: number): string {\n if (percentage >= this.config.contextAutoSaveThreshold) return 'critical';\n if (percentage >= this.config.contextCriticalThreshold) return 'high';\n if (percentage >= this.config.contextWarningThreshold) return 'warning';\n return 'ok';\n }\n\n /**\n * Get current monitor status\n */\n getStatus(): {\n isMonitoring: boolean;\n lastActivity: Date;\n contextUsage: typeof this.lastContextCheck;\n config: MonitorConfig;\n } {\n return {\n isMonitoring: this.isMonitoring,\n lastActivity: this.lastActivityTime,\n contextUsage: this.lastContextCheck,\n config: this.config,\n };\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<MonitorConfig>): void {\n this.config = { ...this.config, ...config };\n this.emit('config:updated', this.config);\n }\n}\n"],
|
|
5
|
+
"mappings": "AAKA,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,wBAAwB;AAGjC,YAAY,QAAQ;AACpB,YAAY,UAAU;AAqBf,MAAM,uBAAuB,aAAa;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAAwB;AAAA,EACxB;AAAA;AAAA,EAGA,mBAIJ,EAAE,QAAQ,GAAG,YAAY,EAAE;AAAA,EAE/B,YACE,cACA,WACA,aACA,QACA;AACA,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