@stackmemoryai/stackmemory 0.5.33 → 0.5.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/dist/agents/core/agent-task-manager.js.map +1 -1
  2. package/dist/cli/commands/clear.js +1 -1
  3. package/dist/cli/commands/clear.js.map +1 -1
  4. package/dist/cli/commands/context.js +1 -1
  5. package/dist/cli/commands/context.js.map +1 -1
  6. package/dist/cli/commands/dashboard.js.map +1 -1
  7. package/dist/cli/commands/discovery.js +1 -1
  8. package/dist/cli/commands/discovery.js.map +1 -1
  9. package/dist/cli/commands/handoff.js +1 -1
  10. package/dist/cli/commands/handoff.js.map +1 -1
  11. package/dist/cli/commands/monitor.js +1 -1
  12. package/dist/cli/commands/monitor.js.map +1 -1
  13. package/dist/cli/commands/quality.js +1 -1
  14. package/dist/cli/commands/quality.js.map +1 -1
  15. package/dist/cli/commands/skills.js +1 -1
  16. package/dist/cli/commands/skills.js.map +1 -1
  17. package/dist/cli/commands/workflow.js +1 -1
  18. package/dist/cli/commands/workflow.js.map +1 -1
  19. package/dist/cli/commands/worktree.js +1 -1
  20. package/dist/cli/commands/worktree.js.map +1 -1
  21. package/dist/cli/index.js +1 -1
  22. package/dist/cli/index.js.map +1 -1
  23. package/dist/core/context/auto-context.js.map +1 -1
  24. package/dist/core/context/compaction-handler.js.map +2 -2
  25. package/dist/core/context/context-bridge.js.map +2 -2
  26. package/dist/core/context/dual-stack-manager.js +1 -1
  27. package/dist/core/context/dual-stack-manager.js.map +1 -1
  28. package/dist/core/context/enhanced-rehydration.js.map +1 -1
  29. package/dist/core/context/frame-database.js +8 -0
  30. package/dist/core/context/frame-database.js.map +2 -2
  31. package/dist/core/context/frame-handoff-manager.js.map +1 -1
  32. package/dist/core/context/frame-lifecycle-hooks.js +119 -0
  33. package/dist/core/context/frame-lifecycle-hooks.js.map +7 -0
  34. package/dist/core/context/frame-stack.js +29 -0
  35. package/dist/core/context/frame-stack.js.map +2 -2
  36. package/dist/core/context/incremental-gc.js.map +2 -2
  37. package/dist/core/context/index.js +4 -22
  38. package/dist/core/context/index.js.map +2 -2
  39. package/dist/core/context/refactored-frame-manager.js +140 -34
  40. package/dist/core/context/refactored-frame-manager.js.map +3 -3
  41. package/dist/core/context/shared-context-layer.js.map +1 -1
  42. package/dist/core/context/stack-merge-resolver.js.map +1 -1
  43. package/dist/core/database/database-adapter.js.map +1 -1
  44. package/dist/core/database/paradedb-adapter.js.map +1 -1
  45. package/dist/core/database/query-router.js.map +1 -1
  46. package/dist/core/database/sqlite-adapter.js.map +1 -1
  47. package/dist/core/digest/frame-digest-integration.js.map +1 -1
  48. package/dist/core/digest/hybrid-digest-generator.js.map +1 -1
  49. package/dist/core/digest/types.js.map +1 -1
  50. package/dist/core/errors/index.js +249 -0
  51. package/dist/core/errors/index.js.map +2 -2
  52. package/dist/core/frame/workflow-templates.js.map +2 -2
  53. package/dist/core/merge/conflict-detector.js.map +1 -1
  54. package/dist/core/merge/resolution-engine.js.map +1 -1
  55. package/dist/core/merge/stack-diff.js.map +1 -1
  56. package/dist/core/models/model-router.js +10 -1
  57. package/dist/core/models/model-router.js.map +2 -2
  58. package/dist/core/monitoring/error-handler.js +37 -270
  59. package/dist/core/monitoring/error-handler.js.map +3 -3
  60. package/dist/core/monitoring/session-monitor.js.map +1 -1
  61. package/dist/core/performance/lazy-context-loader.js.map +1 -1
  62. package/dist/core/performance/optimized-frame-context.js.map +1 -1
  63. package/dist/core/retrieval/context-retriever.js.map +1 -1
  64. package/dist/core/retrieval/graph-retrieval.js.map +1 -1
  65. package/dist/core/retrieval/hierarchical-retrieval.js.map +1 -1
  66. package/dist/core/retrieval/llm-context-retrieval.js.map +1 -1
  67. package/dist/core/retrieval/retrieval-benchmarks.js.map +1 -1
  68. package/dist/core/retrieval/summary-generator.js.map +1 -1
  69. package/dist/core/retrieval/types.js.map +1 -1
  70. package/dist/core/storage/chromadb-adapter.js.map +1 -1
  71. package/dist/core/storage/infinite-storage.js.map +1 -1
  72. package/dist/core/storage/two-tier-storage.js.map +1 -1
  73. package/dist/features/tasks/task-aware-context.js.map +1 -1
  74. package/dist/features/web/server/index.js +1 -1
  75. package/dist/features/web/server/index.js.map +1 -1
  76. package/dist/hooks/schemas.js +50 -0
  77. package/dist/hooks/schemas.js.map +2 -2
  78. package/dist/hooks/sms-action-runner.js +4 -0
  79. package/dist/hooks/sms-action-runner.js.map +2 -2
  80. package/dist/hooks/whatsapp-commands.js +142 -2
  81. package/dist/hooks/whatsapp-commands.js.map +2 -2
  82. package/dist/hooks/whatsapp-sync.js +34 -0
  83. package/dist/hooks/whatsapp-sync.js.map +2 -2
  84. package/dist/index.js +1 -1
  85. package/dist/index.js.map +1 -1
  86. package/dist/integrations/mcp/handlers/context-handlers.js.map +1 -1
  87. package/dist/integrations/mcp/handlers/discovery-handlers.js.map +1 -1
  88. package/dist/integrations/mcp/server.js +1 -1
  89. package/dist/integrations/mcp/server.js.map +1 -1
  90. package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js +1 -1
  91. package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js.map +1 -1
  92. package/dist/integrations/ralph/context/stackmemory-context-loader.js +1 -1
  93. package/dist/integrations/ralph/context/stackmemory-context-loader.js.map +1 -1
  94. package/dist/integrations/ralph/learning/pattern-learner.js +1 -1
  95. package/dist/integrations/ralph/learning/pattern-learner.js.map +1 -1
  96. package/dist/integrations/ralph/orchestration/multi-loop-orchestrator.js +1 -1
  97. package/dist/integrations/ralph/orchestration/multi-loop-orchestrator.js.map +1 -1
  98. package/dist/integrations/ralph/swarm/swarm-coordinator.js +1 -1
  99. package/dist/integrations/ralph/swarm/swarm-coordinator.js.map +1 -1
  100. package/dist/integrations/ralph/visualization/ralph-debugger.js +1 -1
  101. package/dist/integrations/ralph/visualization/ralph-debugger.js.map +1 -1
  102. package/dist/mcp/stackmemory-mcp-server.js +1 -1
  103. package/dist/mcp/stackmemory-mcp-server.js.map +1 -1
  104. package/dist/skills/claude-skills.js.map +1 -1
  105. package/dist/skills/recursive-agent-orchestrator.js.map +1 -1
  106. package/dist/skills/unified-rlm-orchestrator.js.map +1 -1
  107. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/core/context/frame-handoff-manager.ts"],
4
- "sourcesContent": ["/**\n * Frame Handoff Manager - STA-100\n * Handles frame transfers between individual and team stacks with approval workflows\n */\n\nimport type { Frame, Event, Anchor } from './frame-manager.js';\nimport {\n DualStackManager,\n type StackContext,\n type HandoffRequest,\n} from './dual-stack-manager.js';\nimport { logger } from '../monitoring/logger.js';\nimport { ValidationError, DatabaseError, ErrorCode } from '../errors/index.js';\nimport {\n validateInput,\n InitiateHandoffSchema,\n HandoffApprovalSchema,\n type InitiateHandoffInput,\n type HandoffApprovalInput,\n} from './validation.js';\n\nexport interface HandoffMetadata {\n initiatedAt: Date;\n initiatorId: string;\n targetUserId?: string;\n targetTeamId?: string;\n frameContext: {\n totalFrames: number;\n frameTypes: string[];\n estimatedSize: number;\n dependencies: string[];\n };\n businessContext?: {\n milestone?: string;\n priority: 'low' | 'medium' | 'high' | 'critical';\n deadline?: Date;\n stakeholders: string[];\n };\n}\n\nexport interface HandoffApproval {\n requestId: string;\n reviewerId: string;\n decision: 'approved' | 'rejected' | 'needs_changes';\n feedback?: string;\n suggestedChanges?: Array<{\n frameId: string;\n suggestion: string;\n reason: string;\n }>;\n reviewedAt: Date;\n}\n\nexport interface HandoffNotification {\n id: string;\n type: 'request' | 'approval' | 'rejection' | 'completion' | 'reminder';\n requestId: string;\n recipientId: string;\n title: string;\n message: string;\n actionRequired: boolean;\n expiresAt?: Date;\n createdAt: Date;\n}\n\nexport interface HandoffProgress {\n requestId: string;\n status:\n | 'pending_review'\n | 'approved'\n | 'in_transfer'\n | 'completed'\n | 'failed'\n | 'cancelled';\n transferredFrames: number;\n totalFrames: number;\n currentStep: string;\n estimatedCompletion?: Date;\n errors: Array<{\n step: string;\n error: string;\n timestamp: Date;\n }>;\n}\n\nexport class FrameHandoffManager {\n private dualStackManager: DualStackManager;\n private activeHandoffs: Map<string, HandoffProgress> = new Map();\n private pendingApprovals: Map<string, HandoffApproval[]> = new Map();\n private notifications: Map<string, HandoffNotification[]> = new Map();\n\n constructor(dualStackManager: DualStackManager) {\n this.dualStackManager = dualStackManager;\n }\n\n /**\n * Initiate a frame handoff with rich metadata and approval workflow\n */\n async initiateHandoff(\n targetStackId: string,\n frameIds: string[],\n metadata: HandoffMetadata,\n targetUserId?: string,\n message?: string\n ): Promise<string> {\n // Validate input parameters\n const input = validateInput(InitiateHandoffSchema, {\n targetStackId,\n frameIds,\n handoffRequest: metadata,\n reviewerId: targetUserId,\n description: message,\n });\n\n try {\n // Check handoff permissions\n await this.dualStackManager\n .getPermissionManager()\n .enforcePermission(\n this.dualStackManager\n .getPermissionManager()\n .createContext(\n input.handoffRequest.initiatorId,\n 'handoff',\n 'handoff',\n input.targetStackId\n )\n );\n\n // Validate frames exist and are transferable\n await this.validateFramesForHandoff(input.frameIds);\n\n // Create enhanced handoff request\n const requestId = await this.dualStackManager.initiateHandoff(\n input.targetStackId,\n input.frameIds,\n input.reviewerId,\n input.description\n );\n\n // Initialize handoff progress tracking\n const progress: HandoffProgress = {\n requestId,\n status: 'pending_review',\n transferredFrames: 0,\n totalFrames: input.frameIds.length,\n currentStep: 'Awaiting approval',\n errors: [],\n };\n\n this.activeHandoffs.set(requestId, progress);\n\n // Create notifications for relevant stakeholders\n await this.createHandoffNotifications(requestId, metadata, targetUserId);\n\n // Set up automatic reminders\n await this.scheduleHandoffReminders(requestId, metadata);\n\n logger.info(`Initiated enhanced handoff: ${requestId}`, {\n frameCount: frameIds.length,\n priority: metadata.businessContext?.priority,\n targetUser: targetUserId,\n });\n\n return requestId;\n } catch (error: unknown) {\n throw new DatabaseError(\n 'Failed to initiate handoff',\n ErrorCode.OPERATION_FAILED,\n { targetStackId, frameIds },\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Submit approval/rejection for handoff request\n */\n async submitHandoffApproval(\n requestId: string,\n approval: Omit<HandoffApproval, 'requestId' | 'reviewedAt'>\n ): Promise<void> {\n // Validate input parameters\n const input = validateInput(HandoffApprovalSchema, {\n ...approval,\n reviewerId: approval.reviewerId,\n });\n const progress = this.activeHandoffs.get(requestId);\n if (!progress) {\n throw new ValidationError(\n `Handoff request not found: ${requestId}`,\n ErrorCode.HANDOFF_REQUEST_EXPIRED\n );\n }\n\n const fullApproval: HandoffApproval = {\n ...input,\n requestId,\n reviewedAt: new Date(),\n };\n\n // Store approval\n const existingApprovals = this.pendingApprovals.get(requestId) || [];\n existingApprovals.push(fullApproval);\n this.pendingApprovals.set(requestId, existingApprovals);\n\n // Update progress based on decision\n if (input.decision === 'approved') {\n progress.status = 'approved';\n progress.currentStep = 'Ready for transfer';\n\n // Automatically start transfer if approved\n await this.executeHandoffTransfer(requestId);\n } else if (input.decision === 'rejected') {\n progress.status = 'failed';\n progress.currentStep = 'Rejected by reviewer';\n progress.errors.push({\n step: 'approval',\n error: input.feedback || 'Request rejected',\n timestamp: new Date(),\n });\n } else if (input.decision === 'needs_changes') {\n progress.status = 'pending_review';\n progress.currentStep = 'Changes requested';\n\n // Notify requester of needed changes\n await this.notifyChangesRequested(requestId, approval);\n }\n\n this.activeHandoffs.set(requestId, progress);\n\n logger.info(`Handoff approval submitted: ${requestId}`, {\n decision: approval.decision,\n reviewer: approval.reviewerId,\n });\n }\n\n /**\n * Execute the actual frame transfer after approval\n */\n private async executeHandoffTransfer(requestId: string): Promise<void> {\n logger.debug('executeHandoffTransfer called', {\n requestId,\n availableHandoffs: Array.from(this.activeHandoffs.keys()),\n });\n const progress = this.activeHandoffs.get(requestId);\n if (!progress) {\n logger.error('Handoff progress not found', {\n requestId,\n availableHandoffs: Array.from(this.activeHandoffs.keys()),\n });\n throw new DatabaseError(\n `Handoff progress not found: ${requestId}`,\n ErrorCode.INVALID_STATE\n );\n }\n\n try {\n logger.debug('Setting progress status to in_transfer', { requestId });\n progress.status = 'in_transfer';\n progress.currentStep = 'Transferring frames';\n progress.estimatedCompletion = new Date(Date.now() + 5 * 60 * 1000); // 5 minutes\n\n // Execute the handoff through DualStackManager\n logger.debug('About to call acceptHandoff', { requestId });\n const result = await this.dualStackManager.acceptHandoff(requestId);\n logger.debug('acceptHandoff returned', {\n requestId,\n success: result.success,\n });\n\n if (result.success) {\n progress.status = 'completed';\n progress.currentStep = 'Transfer completed';\n progress.transferredFrames = result.mergedFrames.length;\n\n // Create completion notifications\n await this.notifyHandoffCompletion(requestId, result);\n\n logger.info(`Handoff transfer completed: ${requestId}`, {\n transferredFrames: progress.transferredFrames,\n conflicts: result.conflictFrames.length,\n });\n } else {\n progress.status = 'failed';\n progress.currentStep = 'Transfer failed';\n\n // Log errors\n result.errors.forEach((error) => {\n progress.errors.push({\n step: 'transfer',\n error: `Frame ${error.frameId}: ${error.error}`,\n timestamp: new Date(),\n });\n });\n\n throw new DatabaseError(\n 'Handoff transfer failed',\n ErrorCode.OPERATION_FAILED,\n { errors: result.errors }\n );\n }\n } catch (error: unknown) {\n progress.status = 'failed';\n progress.currentStep = 'Transfer error';\n progress.errors.push({\n step: 'transfer',\n error: error instanceof Error ? error.message : String(error),\n timestamp: new Date(),\n });\n\n logger.error(`Handoff transfer failed: ${requestId}`, error);\n throw error;\n } finally {\n this.activeHandoffs.set(requestId, progress);\n }\n }\n\n /**\n * Get handoff progress and status\n */\n async getHandoffProgress(requestId: string): Promise<HandoffProgress | null> {\n return this.activeHandoffs.get(requestId) || null;\n }\n\n /**\n * Cancel a pending handoff request\n */\n async cancelHandoff(requestId: string, reason: string): Promise<void> {\n const progress = this.activeHandoffs.get(requestId);\n if (!progress) {\n throw new DatabaseError(\n `Handoff request not found: ${requestId}`,\n ErrorCode.RESOURCE_NOT_FOUND\n );\n }\n\n if (progress.status === 'in_transfer') {\n throw new DatabaseError(\n 'Cannot cancel handoff that is currently transferring',\n ErrorCode.INVALID_STATE\n );\n }\n\n progress.status = 'cancelled';\n progress.currentStep = 'Cancelled by user';\n progress.errors.push({\n step: 'cancellation',\n error: reason,\n timestamp: new Date(),\n });\n\n this.activeHandoffs.set(requestId, progress);\n\n // Notify relevant parties\n await this.notifyHandoffCancellation(requestId, reason);\n\n logger.info(`Handoff cancelled: ${requestId}`, { reason });\n }\n\n /**\n * Get all active handoffs for a user or team\n */\n async getActiveHandoffs(\n userId?: string,\n teamId?: string\n ): Promise<HandoffProgress[]> {\n const handoffs = Array.from(this.activeHandoffs.values());\n\n // Filter by user/team if specified\n if (userId || teamId) {\n // Would need to cross-reference with handoff metadata\n return handoffs.filter(\n (handoff) =>\n handoff.status === 'pending_review' ||\n handoff.status === 'approved' ||\n handoff.status === 'in_transfer'\n );\n }\n\n return handoffs;\n }\n\n /**\n * Get notifications for a user\n */\n async getUserNotifications(userId: string): Promise<HandoffNotification[]> {\n return this.notifications.get(userId) || [];\n }\n\n /**\n * Mark notification as read\n */\n async markNotificationRead(\n notificationId: string,\n userId: string\n ): Promise<void> {\n const userNotifications = this.notifications.get(userId) || [];\n const updatedNotifications = userNotifications.filter(\n (n) => n.id !== notificationId\n );\n this.notifications.set(userId, updatedNotifications);\n }\n\n /**\n * Validate frames are suitable for handoff\n */\n private async validateFramesForHandoff(frameIds: string[]): Promise<void> {\n const activeStack = this.dualStackManager.getActiveStack();\n\n for (const frameId of frameIds) {\n const frame = await activeStack.getFrame(frameId);\n if (!frame) {\n throw new DatabaseError(\n `Frame not found: ${frameId}`,\n ErrorCode.RESOURCE_NOT_FOUND\n );\n }\n\n // Check if frame is in a transferable state\n if (frame.state === 'active') {\n logger.warn(`Transferring active frame: ${frameId}`, {\n frameName: frame.name,\n });\n }\n }\n }\n\n /**\n * Create notifications for handoff stakeholders\n */\n private async createHandoffNotifications(\n requestId: string,\n metadata: HandoffMetadata,\n targetUserId?: string\n ): Promise<void> {\n const notifications: HandoffNotification[] = [];\n\n // Notify target user\n if (targetUserId) {\n notifications.push({\n id: `${requestId}-target`,\n type: 'request',\n requestId,\n recipientId: targetUserId,\n title: 'Frame Handoff Request',\n message: `${metadata.initiatorId} wants to transfer ${metadata.frameContext.totalFrames} frames to you`,\n actionRequired: true,\n expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),\n createdAt: new Date(),\n });\n }\n\n // Notify stakeholders\n if (metadata.businessContext?.stakeholders) {\n for (const stakeholderId of metadata.businessContext.stakeholders) {\n notifications.push({\n id: `${requestId}-stakeholder-${stakeholderId}`,\n type: 'request',\n requestId,\n recipientId: stakeholderId,\n title: 'Frame Handoff Notification',\n message: `Frame transfer initiated for ${metadata.businessContext?.milestone || 'project milestone'}`,\n actionRequired: false,\n createdAt: new Date(),\n });\n }\n }\n\n // Store notifications\n for (const notification of notifications) {\n const userNotifications =\n this.notifications.get(notification.recipientId) || [];\n userNotifications.push(notification);\n this.notifications.set(notification.recipientId, userNotifications);\n }\n }\n\n /**\n * Schedule reminder notifications\n */\n private async scheduleHandoffReminders(\n requestId: string,\n metadata: HandoffMetadata\n ): Promise<void> {\n // Schedule reminder in 4 hours if high priority\n if (\n metadata.businessContext?.priority === 'high' ||\n metadata.businessContext?.priority === 'critical'\n ) {\n setTimeout(\n async () => {\n const progress = this.activeHandoffs.get(requestId);\n if (progress && progress.status === 'pending_review') {\n await this.sendHandoffReminder(requestId, metadata);\n }\n },\n 4 * 60 * 60 * 1000\n ); // 4 hours\n }\n }\n\n /**\n * Send handoff reminder\n */\n private async sendHandoffReminder(\n requestId: string,\n metadata: HandoffMetadata\n ): Promise<void> {\n const progress = this.activeHandoffs.get(requestId);\n if (!progress || progress.status !== 'pending_review') {\n return;\n }\n\n const reminderNotification: HandoffNotification = {\n id: `${requestId}-reminder-${Date.now()}`,\n type: 'reminder',\n requestId,\n recipientId: metadata.targetUserId || 'unknown',\n title: '\u23F0 Handoff Request Reminder',\n message: `Reminder: ${metadata.initiatorId} is waiting for approval on ${metadata.frameContext.totalFrames} frames. Priority: ${metadata.businessContext?.priority || 'medium'}`,\n actionRequired: true,\n expiresAt: new Date(Date.now() + 12 * 60 * 60 * 1000), // 12 hours\n createdAt: new Date(),\n };\n\n // Store the notification\n if (metadata.targetUserId) {\n const userNotifications =\n this.notifications.get(metadata.targetUserId) || [];\n userNotifications.push(reminderNotification);\n this.notifications.set(metadata.targetUserId, userNotifications);\n\n logger.info(`Sent handoff reminder: ${requestId}`, {\n priority: metadata.businessContext?.priority,\n recipient: metadata.targetUserId,\n });\n }\n\n // Also notify stakeholders\n if (metadata.businessContext?.stakeholders) {\n for (const stakeholderId of metadata.businessContext.stakeholders) {\n const stakeholderNotification: HandoffNotification = {\n ...reminderNotification,\n id: `${requestId}-reminder-stakeholder-${stakeholderId}-${Date.now()}`,\n recipientId: stakeholderId,\n title: '\uD83D\uDCCB Handoff Status Update',\n message: `Pending handoff approval: ${metadata.businessContext?.milestone || 'development work'} requires attention`,\n actionRequired: false,\n };\n\n const stakeholderNotifications =\n this.notifications.get(stakeholderId) || [];\n stakeholderNotifications.push(stakeholderNotification);\n this.notifications.set(stakeholderId, stakeholderNotifications);\n }\n }\n }\n\n /**\n * Notify when changes are requested\n */\n private async notifyChangesRequested(\n requestId: string,\n approval: Omit<HandoffApproval, 'requestId' | 'reviewedAt'>\n ): Promise<void> {\n const progress = this.activeHandoffs.get(requestId);\n if (!progress) return;\n\n // Find the original requester (we'll need to enhance this with better metadata tracking)\n const changeRequestNotification: HandoffNotification = {\n id: `${requestId}-changes-${Date.now()}`,\n type: 'request',\n requestId,\n recipientId: 'requester', // TODO: Get actual requester from handoff metadata\n title: 'Changes Requested for Handoff',\n message: `${approval.reviewerId} has requested changes: ${approval.feedback || 'See detailed suggestions'}`,\n actionRequired: true,\n expiresAt: new Date(Date.now() + 48 * 60 * 60 * 1000), // 48 hours\n createdAt: new Date(),\n };\n\n // Store notification (for now using a placeholder recipient)\n const notifications = this.notifications.get('requester') || [];\n notifications.push(changeRequestNotification);\n this.notifications.set('requester', notifications);\n\n // Log detailed feedback and suggestions\n logger.info(`Changes requested for handoff: ${requestId}`, {\n reviewer: approval.reviewerId,\n feedback: approval.feedback,\n suggestedChangesCount: approval.suggestedChanges?.length || 0,\n });\n\n if (approval.suggestedChanges && approval.suggestedChanges.length > 0) {\n logger.info(`Detailed change suggestions:`, {\n requestId,\n suggestions: approval.suggestedChanges.map((change) => ({\n frameId: change.frameId,\n suggestion: change.suggestion,\n reason: change.reason,\n })),\n });\n }\n }\n\n /**\n * Notify handoff completion\n */\n private async notifyHandoffCompletion(\n requestId: string,\n result: any\n ): Promise<void> {\n const progress = this.activeHandoffs.get(requestId);\n if (!progress) return;\n\n // Create completion notification\n const completionNotification: HandoffNotification = {\n id: `${requestId}-completion-${Date.now()}`,\n type: 'completion',\n requestId,\n recipientId: 'all', // Will be distributed to all stakeholders\n title: 'Handoff Completed Successfully',\n message: `Frame transfer completed: ${result.mergedFrames.length} frames transferred${result.conflictFrames.length > 0 ? `, ${result.conflictFrames.length} conflicts resolved` : ''}`,\n actionRequired: false,\n createdAt: new Date(),\n };\n\n // Notify all stakeholders from the notifications map\n const allUsers = Array.from(this.notifications.keys());\n for (const userId of allUsers) {\n const userSpecificNotification: HandoffNotification = {\n ...completionNotification,\n id: `${requestId}-completion-${userId}-${Date.now()}`,\n recipientId: userId,\n };\n\n const userNotifications = this.notifications.get(userId) || [];\n userNotifications.push(userSpecificNotification);\n this.notifications.set(userId, userNotifications);\n }\n\n logger.info(`Handoff completed: ${requestId}`, {\n mergedFrames: result.mergedFrames.length,\n conflicts: result.conflictFrames.length,\n notifiedUsers: allUsers.length,\n });\n\n // Log detailed completion statistics\n if (result.conflictFrames.length > 0) {\n logger.info(`Handoff completion details:`, {\n requestId,\n transferredFrames: result.mergedFrames.map(\n (f: any) => f.frameId || f.id\n ),\n conflictFrames: result.conflictFrames.map(\n (f: any) => f.frameId || f.id\n ),\n });\n }\n }\n\n /**\n * Notify handoff cancellation\n */\n private async notifyHandoffCancellation(\n requestId: string,\n reason: string\n ): Promise<void> {\n // Create cancellation notification\n const cancellationNotification: HandoffNotification = {\n id: `${requestId}-cancellation-${Date.now()}`,\n type: 'request', // Using 'request' type as it's informational\n requestId,\n recipientId: 'all', // Will be distributed to all stakeholders\n title: 'Handoff Cancelled',\n message: `Handoff request has been cancelled. Reason: ${reason}`,\n actionRequired: false,\n createdAt: new Date(),\n };\n\n // Notify all users who have been involved in this handoff\n const allUsers = Array.from(this.notifications.keys());\n for (const userId of allUsers) {\n const userSpecificNotification: HandoffNotification = {\n ...cancellationNotification,\n id: `${requestId}-cancellation-${userId}-${Date.now()}`,\n recipientId: userId,\n };\n\n const userNotifications = this.notifications.get(userId) || [];\n userNotifications.push(userSpecificNotification);\n this.notifications.set(userId, userNotifications);\n }\n\n logger.info(`Handoff cancelled: ${requestId}`, {\n reason,\n notifiedUsers: allUsers.length,\n });\n }\n\n /**\n * Get handoff analytics and metrics\n */\n async getHandoffMetrics(timeRange?: { start: Date; end: Date }): Promise<{\n totalHandoffs: number;\n completedHandoffs: number;\n averageProcessingTime: number;\n topFrameTypes: Array<{ type: string; count: number }>;\n collaborationPatterns: Array<{\n sourceUser: string;\n targetUser: string;\n count: number;\n }>;\n }> {\n const handoffs = Array.from(this.activeHandoffs.values());\n\n // Filter by time range if specified\n const filteredHandoffs = timeRange\n ? handoffs.filter((h) => {\n // Would need to add timestamps to track creation time\n return true; // Placeholder\n })\n : handoffs;\n\n const completedHandoffs = filteredHandoffs.filter(\n (h) => h.status === 'completed'\n );\n\n return {\n totalHandoffs: filteredHandoffs.length,\n completedHandoffs: completedHandoffs.length,\n averageProcessingTime:\n this.calculateAverageProcessingTime(completedHandoffs),\n topFrameTypes: this.analyzeFrameTypes(filteredHandoffs),\n collaborationPatterns:\n this.analyzeCollaborationPatterns(filteredHandoffs),\n };\n }\n\n private calculateAverageProcessingTime(handoffs: HandoffProgress[]): number {\n if (handoffs.length === 0) return 0;\n\n let totalProcessingTime = 0;\n let validHandoffs = 0;\n\n for (const handoff of handoffs) {\n // Only calculate for completed handoffs that have timing data\n if (handoff.status === 'completed' && handoff.estimatedCompletion) {\n // Estimate processing time based on frame count and complexity\n // This is a simplified calculation - in practice you'd track actual timestamps\n const frameComplexity = handoff.totalFrames * 0.5; // Base time per frame\n const errorPenalty = handoff.errors.length * 2; // Extra time for errors\n const processingTime = Math.max(1, frameComplexity + errorPenalty);\n\n totalProcessingTime += processingTime;\n validHandoffs++;\n }\n }\n\n return validHandoffs > 0\n ? Math.round(totalProcessingTime / validHandoffs)\n : 0;\n }\n\n private analyzeFrameTypes(\n handoffs: HandoffProgress[]\n ): Array<{ type: string; count: number }> {\n const frameTypeCount = new Map<string, number>();\n\n for (const handoff of handoffs) {\n // Extract frame type information from handoff metadata\n // This would need to be enhanced with actual frame type tracking\n const estimatedTypes = this.estimateFrameTypes(handoff);\n\n for (const type of estimatedTypes) {\n frameTypeCount.set(type, (frameTypeCount.get(type) || 0) + 1);\n }\n }\n\n return Array.from(frameTypeCount.entries())\n .map(([type, count]) => ({ type, count }))\n .sort((a, b) => b.count - a.count)\n .slice(0, 10); // Top 10 frame types\n }\n\n private estimateFrameTypes(handoff: HandoffProgress): string[] {\n // Simplified frame type estimation based on handoff characteristics\n const types: string[] = [];\n\n if (handoff.totalFrames > 10) {\n types.push('bulk_transfer');\n }\n if (handoff.errors.length > 0) {\n types.push('complex_handoff');\n }\n if (handoff.transferredFrames === handoff.totalFrames) {\n types.push('complete_transfer');\n } else {\n types.push('partial_transfer');\n }\n\n // Add some common frame types based on patterns\n types.push('development', 'collaboration');\n\n return types;\n }\n\n private analyzeCollaborationPatterns(\n handoffs: HandoffProgress[]\n ): Array<{ sourceUser: string; targetUser: string; count: number }> {\n const collaborationCount = new Map<string, number>();\n\n for (const handoff of handoffs) {\n // Extract collaboration pattern from handoff data\n // Note: This is simplified - we'd need to track actual source/target users\n const pattern = this.extractCollaborationPattern(handoff);\n if (pattern) {\n const key = `${pattern.sourceUser}->${pattern.targetUser}`;\n collaborationCount.set(key, (collaborationCount.get(key) || 0) + 1);\n }\n }\n\n return Array.from(collaborationCount.entries())\n .map(([pattern, count]) => {\n const [sourceUser, targetUser] = pattern.split('->');\n return { sourceUser, targetUser, count };\n })\n .sort((a, b) => b.count - a.count)\n .slice(0, 20); // Top 20 collaboration patterns\n }\n\n private extractCollaborationPattern(\n handoff: HandoffProgress\n ): { sourceUser: string; targetUser: string } | null {\n // Simplified pattern extraction - in practice this would come from handoff metadata\n // For now, we'll create sample patterns based on handoff characteristics\n\n if (handoff.status === 'completed') {\n return {\n sourceUser: 'developer',\n targetUser: 'reviewer',\n };\n } else if (handoff.status === 'failed') {\n return {\n sourceUser: 'developer',\n targetUser: 'lead',\n };\n }\n\n return null;\n }\n\n /**\n * Real-time collaboration features\n */\n\n /**\n * Get real-time handoff status updates\n */\n async getHandoffStatusStream(\n requestId: string\n ): Promise<AsyncIterableIterator<HandoffProgress>> {\n const progress = this.activeHandoffs.get(requestId);\n if (!progress) {\n throw new DatabaseError(\n `Handoff request not found: ${requestId}`,\n ErrorCode.RESOURCE_NOT_FOUND\n );\n }\n\n // Simple implementation - in a real system this would use WebSockets or Server-Sent Events\n const self = this;\n return {\n async *[Symbol.asyncIterator]() {\n let lastStatus = progress.status;\n while (\n lastStatus !== 'completed' &&\n lastStatus !== 'failed' &&\n lastStatus !== 'cancelled'\n ) {\n const currentProgress = self.activeHandoffs.get(requestId);\n if (currentProgress && currentProgress.status !== lastStatus) {\n lastStatus = currentProgress.status;\n yield currentProgress;\n }\n // Simulate real-time polling\n await new Promise((resolve) => setTimeout(resolve, 1000));\n }\n },\n };\n }\n\n /**\n * Update handoff progress in real-time\n */\n async updateHandoffProgress(\n requestId: string,\n update: Partial<HandoffProgress>\n ): Promise<void> {\n let progress = this.activeHandoffs.get(requestId);\n\n // If progress doesn't exist and update includes required fields, create it\n if (\n !progress &&\n update.requestId &&\n update.status &&\n update.totalFrames !== undefined\n ) {\n progress = {\n requestId: update.requestId,\n status: update.status,\n transferredFrames: 0,\n totalFrames: update.totalFrames,\n currentStep: 'Initialized',\n errors: [],\n ...update,\n };\n } else if (!progress) {\n throw new DatabaseError(\n `Handoff request not found: ${requestId}`,\n ErrorCode.RESOURCE_NOT_FOUND\n );\n } else {\n // Update existing progress with provided fields\n progress = {\n ...progress,\n ...update,\n };\n }\n\n this.activeHandoffs.set(requestId, progress);\n\n logger.info(`Handoff progress updated: ${requestId}`, {\n status: progress.status,\n currentStep: progress.currentStep,\n transferredFrames: progress.transferredFrames,\n });\n\n // Notify stakeholders of progress update\n await this.notifyProgressUpdate(requestId, progress);\n }\n\n /**\n * Notify stakeholders of progress updates\n */\n private async notifyProgressUpdate(\n requestId: string,\n progress: HandoffProgress\n ): Promise<void> {\n const updateNotification: HandoffNotification = {\n id: `${requestId}-progress-${Date.now()}`,\n type: 'request',\n requestId,\n recipientId: 'all',\n title: 'Handoff Progress Update',\n message: `Status: ${progress.status} | Step: ${progress.currentStep} | Progress: ${progress.transferredFrames}/${progress.totalFrames} frames`,\n actionRequired: false,\n createdAt: new Date(),\n };\n\n // Distribute to all stakeholders\n const allUsers = Array.from(this.notifications.keys());\n for (const userId of allUsers) {\n const userNotifications = this.notifications.get(userId) || [];\n userNotifications.push({\n ...updateNotification,\n id: `${requestId}-progress-${userId}-${Date.now()}`,\n recipientId: userId,\n });\n this.notifications.set(userId, userNotifications);\n }\n }\n\n /**\n * Get active handoffs with real-time filtering\n */\n async getActiveHandoffsRealTime(filters?: {\n status?: HandoffProgress['status'];\n userId?: string;\n priority?: 'low' | 'medium' | 'high' | 'critical';\n }): Promise<HandoffProgress[]> {\n let handoffs = Array.from(this.activeHandoffs.values());\n\n if (filters?.status) {\n handoffs = handoffs.filter((h) => h.status === filters.status);\n }\n\n if (filters?.userId) {\n // In a real implementation, we'd have proper user tracking in handoff metadata\n // For now, filter based on requestId pattern or other heuristics\n handoffs = handoffs.filter((h) =>\n h.requestId.includes(filters.userId || '')\n );\n }\n\n if (filters?.priority) {\n // Filter by priority (this would need priority tracking in HandoffProgress)\n // For now, estimate priority based on frame count and errors\n handoffs = handoffs.filter((h) => {\n const estimatedPriority = this.estimateHandoffPriority(h);\n return estimatedPriority === filters.priority;\n });\n }\n\n return handoffs.sort((a, b) => {\n // Sort by status priority, then by creation time\n const statusPriority = {\n in_transfer: 4,\n approved: 3,\n pending_review: 2,\n completed: 1,\n failed: 1,\n cancelled: 0,\n };\n return (statusPriority[b.status] || 0) - (statusPriority[a.status] || 0);\n });\n }\n\n private estimateHandoffPriority(\n handoff: HandoffProgress\n ): 'low' | 'medium' | 'high' | 'critical' {\n if (handoff.errors.length > 2 || handoff.totalFrames > 50)\n return 'critical';\n if (handoff.errors.length > 0 || handoff.totalFrames > 20) return 'high';\n if (handoff.totalFrames > 5) return 'medium';\n return 'low';\n }\n\n /**\n * Bulk handoff operations for team collaboration\n */\n async bulkHandoffOperation(operation: {\n action: 'approve' | 'reject' | 'cancel';\n requestIds: string[];\n reviewerId: string;\n feedback?: string;\n }): Promise<{\n successful: string[];\n failed: Array<{ requestId: string; error: string }>;\n }> {\n const results = {\n successful: [],\n failed: [] as Array<{ requestId: string; error: string }>,\n };\n\n for (const requestId of operation.requestIds) {\n try {\n switch (operation.action) {\n case 'approve':\n await this.submitHandoffApproval(requestId, {\n reviewerId: operation.reviewerId,\n decision: 'approved',\n feedback: operation.feedback,\n });\n results.successful.push(requestId);\n break;\n\n case 'reject':\n await this.submitHandoffApproval(requestId, {\n reviewerId: operation.reviewerId,\n decision: 'rejected',\n feedback: operation.feedback || 'Bulk rejection',\n });\n results.successful.push(requestId);\n break;\n\n case 'cancel':\n await this.cancelHandoff(\n requestId,\n operation.feedback || 'Bulk cancellation'\n );\n results.successful.push(requestId);\n break;\n }\n } catch (error: unknown) {\n results.failed.push({\n requestId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n logger.info(`Bulk handoff operation completed`, {\n action: operation.action,\n successful: results.successful.length,\n failed: results.failed.length,\n reviewerId: operation.reviewerId,\n });\n\n return results;\n }\n\n /**\n * Enhanced notification management with cleanup\n */\n async cleanupExpiredNotifications(userId?: string): Promise<number> {\n let cleanedCount = 0;\n const now = new Date();\n\n const userIds = userId ? [userId] : Array.from(this.notifications.keys());\n\n for (const uid of userIds) {\n const userNotifications = this.notifications.get(uid) || [];\n const activeNotifications = userNotifications.filter((notification) => {\n if (notification.expiresAt && notification.expiresAt < now) {\n cleanedCount++;\n return false;\n }\n return true;\n });\n\n this.notifications.set(uid, activeNotifications);\n }\n\n if (cleanedCount > 0) {\n logger.info(`Cleaned up expired notifications`, {\n count: cleanedCount,\n userId: userId || 'all',\n });\n }\n\n return cleanedCount;\n }\n}\n"],
4
+ "sourcesContent": ["/**\n * Frame Handoff Manager - STA-100\n * Handles frame transfers between individual and team stacks with approval workflows\n */\n\nimport type { Frame, Event, Anchor } from './frame-types.js';\nimport {\n DualStackManager,\n type StackContext,\n type HandoffRequest,\n} from './dual-stack-manager.js';\nimport { logger } from '../monitoring/logger.js';\nimport { ValidationError, DatabaseError, ErrorCode } from '../errors/index.js';\nimport {\n validateInput,\n InitiateHandoffSchema,\n HandoffApprovalSchema,\n type InitiateHandoffInput,\n type HandoffApprovalInput,\n} from './validation.js';\n\nexport interface HandoffMetadata {\n initiatedAt: Date;\n initiatorId: string;\n targetUserId?: string;\n targetTeamId?: string;\n frameContext: {\n totalFrames: number;\n frameTypes: string[];\n estimatedSize: number;\n dependencies: string[];\n };\n businessContext?: {\n milestone?: string;\n priority: 'low' | 'medium' | 'high' | 'critical';\n deadline?: Date;\n stakeholders: string[];\n };\n}\n\nexport interface HandoffApproval {\n requestId: string;\n reviewerId: string;\n decision: 'approved' | 'rejected' | 'needs_changes';\n feedback?: string;\n suggestedChanges?: Array<{\n frameId: string;\n suggestion: string;\n reason: string;\n }>;\n reviewedAt: Date;\n}\n\nexport interface HandoffNotification {\n id: string;\n type: 'request' | 'approval' | 'rejection' | 'completion' | 'reminder';\n requestId: string;\n recipientId: string;\n title: string;\n message: string;\n actionRequired: boolean;\n expiresAt?: Date;\n createdAt: Date;\n}\n\nexport interface HandoffProgress {\n requestId: string;\n status:\n | 'pending_review'\n | 'approved'\n | 'in_transfer'\n | 'completed'\n | 'failed'\n | 'cancelled';\n transferredFrames: number;\n totalFrames: number;\n currentStep: string;\n estimatedCompletion?: Date;\n errors: Array<{\n step: string;\n error: string;\n timestamp: Date;\n }>;\n}\n\nexport class FrameHandoffManager {\n private dualStackManager: DualStackManager;\n private activeHandoffs: Map<string, HandoffProgress> = new Map();\n private pendingApprovals: Map<string, HandoffApproval[]> = new Map();\n private notifications: Map<string, HandoffNotification[]> = new Map();\n\n constructor(dualStackManager: DualStackManager) {\n this.dualStackManager = dualStackManager;\n }\n\n /**\n * Initiate a frame handoff with rich metadata and approval workflow\n */\n async initiateHandoff(\n targetStackId: string,\n frameIds: string[],\n metadata: HandoffMetadata,\n targetUserId?: string,\n message?: string\n ): Promise<string> {\n // Validate input parameters\n const input = validateInput(InitiateHandoffSchema, {\n targetStackId,\n frameIds,\n handoffRequest: metadata,\n reviewerId: targetUserId,\n description: message,\n });\n\n try {\n // Check handoff permissions\n await this.dualStackManager\n .getPermissionManager()\n .enforcePermission(\n this.dualStackManager\n .getPermissionManager()\n .createContext(\n input.handoffRequest.initiatorId,\n 'handoff',\n 'handoff',\n input.targetStackId\n )\n );\n\n // Validate frames exist and are transferable\n await this.validateFramesForHandoff(input.frameIds);\n\n // Create enhanced handoff request\n const requestId = await this.dualStackManager.initiateHandoff(\n input.targetStackId,\n input.frameIds,\n input.reviewerId,\n input.description\n );\n\n // Initialize handoff progress tracking\n const progress: HandoffProgress = {\n requestId,\n status: 'pending_review',\n transferredFrames: 0,\n totalFrames: input.frameIds.length,\n currentStep: 'Awaiting approval',\n errors: [],\n };\n\n this.activeHandoffs.set(requestId, progress);\n\n // Create notifications for relevant stakeholders\n await this.createHandoffNotifications(requestId, metadata, targetUserId);\n\n // Set up automatic reminders\n await this.scheduleHandoffReminders(requestId, metadata);\n\n logger.info(`Initiated enhanced handoff: ${requestId}`, {\n frameCount: frameIds.length,\n priority: metadata.businessContext?.priority,\n targetUser: targetUserId,\n });\n\n return requestId;\n } catch (error: unknown) {\n throw new DatabaseError(\n 'Failed to initiate handoff',\n ErrorCode.OPERATION_FAILED,\n { targetStackId, frameIds },\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Submit approval/rejection for handoff request\n */\n async submitHandoffApproval(\n requestId: string,\n approval: Omit<HandoffApproval, 'requestId' | 'reviewedAt'>\n ): Promise<void> {\n // Validate input parameters\n const input = validateInput(HandoffApprovalSchema, {\n ...approval,\n reviewerId: approval.reviewerId,\n });\n const progress = this.activeHandoffs.get(requestId);\n if (!progress) {\n throw new ValidationError(\n `Handoff request not found: ${requestId}`,\n ErrorCode.HANDOFF_REQUEST_EXPIRED\n );\n }\n\n const fullApproval: HandoffApproval = {\n ...input,\n requestId,\n reviewedAt: new Date(),\n };\n\n // Store approval\n const existingApprovals = this.pendingApprovals.get(requestId) || [];\n existingApprovals.push(fullApproval);\n this.pendingApprovals.set(requestId, existingApprovals);\n\n // Update progress based on decision\n if (input.decision === 'approved') {\n progress.status = 'approved';\n progress.currentStep = 'Ready for transfer';\n\n // Automatically start transfer if approved\n await this.executeHandoffTransfer(requestId);\n } else if (input.decision === 'rejected') {\n progress.status = 'failed';\n progress.currentStep = 'Rejected by reviewer';\n progress.errors.push({\n step: 'approval',\n error: input.feedback || 'Request rejected',\n timestamp: new Date(),\n });\n } else if (input.decision === 'needs_changes') {\n progress.status = 'pending_review';\n progress.currentStep = 'Changes requested';\n\n // Notify requester of needed changes\n await this.notifyChangesRequested(requestId, approval);\n }\n\n this.activeHandoffs.set(requestId, progress);\n\n logger.info(`Handoff approval submitted: ${requestId}`, {\n decision: approval.decision,\n reviewer: approval.reviewerId,\n });\n }\n\n /**\n * Execute the actual frame transfer after approval\n */\n private async executeHandoffTransfer(requestId: string): Promise<void> {\n logger.debug('executeHandoffTransfer called', {\n requestId,\n availableHandoffs: Array.from(this.activeHandoffs.keys()),\n });\n const progress = this.activeHandoffs.get(requestId);\n if (!progress) {\n logger.error('Handoff progress not found', {\n requestId,\n availableHandoffs: Array.from(this.activeHandoffs.keys()),\n });\n throw new DatabaseError(\n `Handoff progress not found: ${requestId}`,\n ErrorCode.INVALID_STATE\n );\n }\n\n try {\n logger.debug('Setting progress status to in_transfer', { requestId });\n progress.status = 'in_transfer';\n progress.currentStep = 'Transferring frames';\n progress.estimatedCompletion = new Date(Date.now() + 5 * 60 * 1000); // 5 minutes\n\n // Execute the handoff through DualStackManager\n logger.debug('About to call acceptHandoff', { requestId });\n const result = await this.dualStackManager.acceptHandoff(requestId);\n logger.debug('acceptHandoff returned', {\n requestId,\n success: result.success,\n });\n\n if (result.success) {\n progress.status = 'completed';\n progress.currentStep = 'Transfer completed';\n progress.transferredFrames = result.mergedFrames.length;\n\n // Create completion notifications\n await this.notifyHandoffCompletion(requestId, result);\n\n logger.info(`Handoff transfer completed: ${requestId}`, {\n transferredFrames: progress.transferredFrames,\n conflicts: result.conflictFrames.length,\n });\n } else {\n progress.status = 'failed';\n progress.currentStep = 'Transfer failed';\n\n // Log errors\n result.errors.forEach((error) => {\n progress.errors.push({\n step: 'transfer',\n error: `Frame ${error.frameId}: ${error.error}`,\n timestamp: new Date(),\n });\n });\n\n throw new DatabaseError(\n 'Handoff transfer failed',\n ErrorCode.OPERATION_FAILED,\n { errors: result.errors }\n );\n }\n } catch (error: unknown) {\n progress.status = 'failed';\n progress.currentStep = 'Transfer error';\n progress.errors.push({\n step: 'transfer',\n error: error instanceof Error ? error.message : String(error),\n timestamp: new Date(),\n });\n\n logger.error(`Handoff transfer failed: ${requestId}`, error);\n throw error;\n } finally {\n this.activeHandoffs.set(requestId, progress);\n }\n }\n\n /**\n * Get handoff progress and status\n */\n async getHandoffProgress(requestId: string): Promise<HandoffProgress | null> {\n return this.activeHandoffs.get(requestId) || null;\n }\n\n /**\n * Cancel a pending handoff request\n */\n async cancelHandoff(requestId: string, reason: string): Promise<void> {\n const progress = this.activeHandoffs.get(requestId);\n if (!progress) {\n throw new DatabaseError(\n `Handoff request not found: ${requestId}`,\n ErrorCode.RESOURCE_NOT_FOUND\n );\n }\n\n if (progress.status === 'in_transfer') {\n throw new DatabaseError(\n 'Cannot cancel handoff that is currently transferring',\n ErrorCode.INVALID_STATE\n );\n }\n\n progress.status = 'cancelled';\n progress.currentStep = 'Cancelled by user';\n progress.errors.push({\n step: 'cancellation',\n error: reason,\n timestamp: new Date(),\n });\n\n this.activeHandoffs.set(requestId, progress);\n\n // Notify relevant parties\n await this.notifyHandoffCancellation(requestId, reason);\n\n logger.info(`Handoff cancelled: ${requestId}`, { reason });\n }\n\n /**\n * Get all active handoffs for a user or team\n */\n async getActiveHandoffs(\n userId?: string,\n teamId?: string\n ): Promise<HandoffProgress[]> {\n const handoffs = Array.from(this.activeHandoffs.values());\n\n // Filter by user/team if specified\n if (userId || teamId) {\n // Would need to cross-reference with handoff metadata\n return handoffs.filter(\n (handoff) =>\n handoff.status === 'pending_review' ||\n handoff.status === 'approved' ||\n handoff.status === 'in_transfer'\n );\n }\n\n return handoffs;\n }\n\n /**\n * Get notifications for a user\n */\n async getUserNotifications(userId: string): Promise<HandoffNotification[]> {\n return this.notifications.get(userId) || [];\n }\n\n /**\n * Mark notification as read\n */\n async markNotificationRead(\n notificationId: string,\n userId: string\n ): Promise<void> {\n const userNotifications = this.notifications.get(userId) || [];\n const updatedNotifications = userNotifications.filter(\n (n) => n.id !== notificationId\n );\n this.notifications.set(userId, updatedNotifications);\n }\n\n /**\n * Validate frames are suitable for handoff\n */\n private async validateFramesForHandoff(frameIds: string[]): Promise<void> {\n const activeStack = this.dualStackManager.getActiveStack();\n\n for (const frameId of frameIds) {\n const frame = await activeStack.getFrame(frameId);\n if (!frame) {\n throw new DatabaseError(\n `Frame not found: ${frameId}`,\n ErrorCode.RESOURCE_NOT_FOUND\n );\n }\n\n // Check if frame is in a transferable state\n if (frame.state === 'active') {\n logger.warn(`Transferring active frame: ${frameId}`, {\n frameName: frame.name,\n });\n }\n }\n }\n\n /**\n * Create notifications for handoff stakeholders\n */\n private async createHandoffNotifications(\n requestId: string,\n metadata: HandoffMetadata,\n targetUserId?: string\n ): Promise<void> {\n const notifications: HandoffNotification[] = [];\n\n // Notify target user\n if (targetUserId) {\n notifications.push({\n id: `${requestId}-target`,\n type: 'request',\n requestId,\n recipientId: targetUserId,\n title: 'Frame Handoff Request',\n message: `${metadata.initiatorId} wants to transfer ${metadata.frameContext.totalFrames} frames to you`,\n actionRequired: true,\n expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),\n createdAt: new Date(),\n });\n }\n\n // Notify stakeholders\n if (metadata.businessContext?.stakeholders) {\n for (const stakeholderId of metadata.businessContext.stakeholders) {\n notifications.push({\n id: `${requestId}-stakeholder-${stakeholderId}`,\n type: 'request',\n requestId,\n recipientId: stakeholderId,\n title: 'Frame Handoff Notification',\n message: `Frame transfer initiated for ${metadata.businessContext?.milestone || 'project milestone'}`,\n actionRequired: false,\n createdAt: new Date(),\n });\n }\n }\n\n // Store notifications\n for (const notification of notifications) {\n const userNotifications =\n this.notifications.get(notification.recipientId) || [];\n userNotifications.push(notification);\n this.notifications.set(notification.recipientId, userNotifications);\n }\n }\n\n /**\n * Schedule reminder notifications\n */\n private async scheduleHandoffReminders(\n requestId: string,\n metadata: HandoffMetadata\n ): Promise<void> {\n // Schedule reminder in 4 hours if high priority\n if (\n metadata.businessContext?.priority === 'high' ||\n metadata.businessContext?.priority === 'critical'\n ) {\n setTimeout(\n async () => {\n const progress = this.activeHandoffs.get(requestId);\n if (progress && progress.status === 'pending_review') {\n await this.sendHandoffReminder(requestId, metadata);\n }\n },\n 4 * 60 * 60 * 1000\n ); // 4 hours\n }\n }\n\n /**\n * Send handoff reminder\n */\n private async sendHandoffReminder(\n requestId: string,\n metadata: HandoffMetadata\n ): Promise<void> {\n const progress = this.activeHandoffs.get(requestId);\n if (!progress || progress.status !== 'pending_review') {\n return;\n }\n\n const reminderNotification: HandoffNotification = {\n id: `${requestId}-reminder-${Date.now()}`,\n type: 'reminder',\n requestId,\n recipientId: metadata.targetUserId || 'unknown',\n title: '\u23F0 Handoff Request Reminder',\n message: `Reminder: ${metadata.initiatorId} is waiting for approval on ${metadata.frameContext.totalFrames} frames. Priority: ${metadata.businessContext?.priority || 'medium'}`,\n actionRequired: true,\n expiresAt: new Date(Date.now() + 12 * 60 * 60 * 1000), // 12 hours\n createdAt: new Date(),\n };\n\n // Store the notification\n if (metadata.targetUserId) {\n const userNotifications =\n this.notifications.get(metadata.targetUserId) || [];\n userNotifications.push(reminderNotification);\n this.notifications.set(metadata.targetUserId, userNotifications);\n\n logger.info(`Sent handoff reminder: ${requestId}`, {\n priority: metadata.businessContext?.priority,\n recipient: metadata.targetUserId,\n });\n }\n\n // Also notify stakeholders\n if (metadata.businessContext?.stakeholders) {\n for (const stakeholderId of metadata.businessContext.stakeholders) {\n const stakeholderNotification: HandoffNotification = {\n ...reminderNotification,\n id: `${requestId}-reminder-stakeholder-${stakeholderId}-${Date.now()}`,\n recipientId: stakeholderId,\n title: '\uD83D\uDCCB Handoff Status Update',\n message: `Pending handoff approval: ${metadata.businessContext?.milestone || 'development work'} requires attention`,\n actionRequired: false,\n };\n\n const stakeholderNotifications =\n this.notifications.get(stakeholderId) || [];\n stakeholderNotifications.push(stakeholderNotification);\n this.notifications.set(stakeholderId, stakeholderNotifications);\n }\n }\n }\n\n /**\n * Notify when changes are requested\n */\n private async notifyChangesRequested(\n requestId: string,\n approval: Omit<HandoffApproval, 'requestId' | 'reviewedAt'>\n ): Promise<void> {\n const progress = this.activeHandoffs.get(requestId);\n if (!progress) return;\n\n // Find the original requester (we'll need to enhance this with better metadata tracking)\n const changeRequestNotification: HandoffNotification = {\n id: `${requestId}-changes-${Date.now()}`,\n type: 'request',\n requestId,\n recipientId: 'requester', // TODO: Get actual requester from handoff metadata\n title: 'Changes Requested for Handoff',\n message: `${approval.reviewerId} has requested changes: ${approval.feedback || 'See detailed suggestions'}`,\n actionRequired: true,\n expiresAt: new Date(Date.now() + 48 * 60 * 60 * 1000), // 48 hours\n createdAt: new Date(),\n };\n\n // Store notification (for now using a placeholder recipient)\n const notifications = this.notifications.get('requester') || [];\n notifications.push(changeRequestNotification);\n this.notifications.set('requester', notifications);\n\n // Log detailed feedback and suggestions\n logger.info(`Changes requested for handoff: ${requestId}`, {\n reviewer: approval.reviewerId,\n feedback: approval.feedback,\n suggestedChangesCount: approval.suggestedChanges?.length || 0,\n });\n\n if (approval.suggestedChanges && approval.suggestedChanges.length > 0) {\n logger.info(`Detailed change suggestions:`, {\n requestId,\n suggestions: approval.suggestedChanges.map((change) => ({\n frameId: change.frameId,\n suggestion: change.suggestion,\n reason: change.reason,\n })),\n });\n }\n }\n\n /**\n * Notify handoff completion\n */\n private async notifyHandoffCompletion(\n requestId: string,\n result: any\n ): Promise<void> {\n const progress = this.activeHandoffs.get(requestId);\n if (!progress) return;\n\n // Create completion notification\n const completionNotification: HandoffNotification = {\n id: `${requestId}-completion-${Date.now()}`,\n type: 'completion',\n requestId,\n recipientId: 'all', // Will be distributed to all stakeholders\n title: 'Handoff Completed Successfully',\n message: `Frame transfer completed: ${result.mergedFrames.length} frames transferred${result.conflictFrames.length > 0 ? `, ${result.conflictFrames.length} conflicts resolved` : ''}`,\n actionRequired: false,\n createdAt: new Date(),\n };\n\n // Notify all stakeholders from the notifications map\n const allUsers = Array.from(this.notifications.keys());\n for (const userId of allUsers) {\n const userSpecificNotification: HandoffNotification = {\n ...completionNotification,\n id: `${requestId}-completion-${userId}-${Date.now()}`,\n recipientId: userId,\n };\n\n const userNotifications = this.notifications.get(userId) || [];\n userNotifications.push(userSpecificNotification);\n this.notifications.set(userId, userNotifications);\n }\n\n logger.info(`Handoff completed: ${requestId}`, {\n mergedFrames: result.mergedFrames.length,\n conflicts: result.conflictFrames.length,\n notifiedUsers: allUsers.length,\n });\n\n // Log detailed completion statistics\n if (result.conflictFrames.length > 0) {\n logger.info(`Handoff completion details:`, {\n requestId,\n transferredFrames: result.mergedFrames.map(\n (f: any) => f.frameId || f.id\n ),\n conflictFrames: result.conflictFrames.map(\n (f: any) => f.frameId || f.id\n ),\n });\n }\n }\n\n /**\n * Notify handoff cancellation\n */\n private async notifyHandoffCancellation(\n requestId: string,\n reason: string\n ): Promise<void> {\n // Create cancellation notification\n const cancellationNotification: HandoffNotification = {\n id: `${requestId}-cancellation-${Date.now()}`,\n type: 'request', // Using 'request' type as it's informational\n requestId,\n recipientId: 'all', // Will be distributed to all stakeholders\n title: 'Handoff Cancelled',\n message: `Handoff request has been cancelled. Reason: ${reason}`,\n actionRequired: false,\n createdAt: new Date(),\n };\n\n // Notify all users who have been involved in this handoff\n const allUsers = Array.from(this.notifications.keys());\n for (const userId of allUsers) {\n const userSpecificNotification: HandoffNotification = {\n ...cancellationNotification,\n id: `${requestId}-cancellation-${userId}-${Date.now()}`,\n recipientId: userId,\n };\n\n const userNotifications = this.notifications.get(userId) || [];\n userNotifications.push(userSpecificNotification);\n this.notifications.set(userId, userNotifications);\n }\n\n logger.info(`Handoff cancelled: ${requestId}`, {\n reason,\n notifiedUsers: allUsers.length,\n });\n }\n\n /**\n * Get handoff analytics and metrics\n */\n async getHandoffMetrics(timeRange?: { start: Date; end: Date }): Promise<{\n totalHandoffs: number;\n completedHandoffs: number;\n averageProcessingTime: number;\n topFrameTypes: Array<{ type: string; count: number }>;\n collaborationPatterns: Array<{\n sourceUser: string;\n targetUser: string;\n count: number;\n }>;\n }> {\n const handoffs = Array.from(this.activeHandoffs.values());\n\n // Filter by time range if specified\n const filteredHandoffs = timeRange\n ? handoffs.filter((h) => {\n // Would need to add timestamps to track creation time\n return true; // Placeholder\n })\n : handoffs;\n\n const completedHandoffs = filteredHandoffs.filter(\n (h) => h.status === 'completed'\n );\n\n return {\n totalHandoffs: filteredHandoffs.length,\n completedHandoffs: completedHandoffs.length,\n averageProcessingTime:\n this.calculateAverageProcessingTime(completedHandoffs),\n topFrameTypes: this.analyzeFrameTypes(filteredHandoffs),\n collaborationPatterns:\n this.analyzeCollaborationPatterns(filteredHandoffs),\n };\n }\n\n private calculateAverageProcessingTime(handoffs: HandoffProgress[]): number {\n if (handoffs.length === 0) return 0;\n\n let totalProcessingTime = 0;\n let validHandoffs = 0;\n\n for (const handoff of handoffs) {\n // Only calculate for completed handoffs that have timing data\n if (handoff.status === 'completed' && handoff.estimatedCompletion) {\n // Estimate processing time based on frame count and complexity\n // This is a simplified calculation - in practice you'd track actual timestamps\n const frameComplexity = handoff.totalFrames * 0.5; // Base time per frame\n const errorPenalty = handoff.errors.length * 2; // Extra time for errors\n const processingTime = Math.max(1, frameComplexity + errorPenalty);\n\n totalProcessingTime += processingTime;\n validHandoffs++;\n }\n }\n\n return validHandoffs > 0\n ? Math.round(totalProcessingTime / validHandoffs)\n : 0;\n }\n\n private analyzeFrameTypes(\n handoffs: HandoffProgress[]\n ): Array<{ type: string; count: number }> {\n const frameTypeCount = new Map<string, number>();\n\n for (const handoff of handoffs) {\n // Extract frame type information from handoff metadata\n // This would need to be enhanced with actual frame type tracking\n const estimatedTypes = this.estimateFrameTypes(handoff);\n\n for (const type of estimatedTypes) {\n frameTypeCount.set(type, (frameTypeCount.get(type) || 0) + 1);\n }\n }\n\n return Array.from(frameTypeCount.entries())\n .map(([type, count]) => ({ type, count }))\n .sort((a, b) => b.count - a.count)\n .slice(0, 10); // Top 10 frame types\n }\n\n private estimateFrameTypes(handoff: HandoffProgress): string[] {\n // Simplified frame type estimation based on handoff characteristics\n const types: string[] = [];\n\n if (handoff.totalFrames > 10) {\n types.push('bulk_transfer');\n }\n if (handoff.errors.length > 0) {\n types.push('complex_handoff');\n }\n if (handoff.transferredFrames === handoff.totalFrames) {\n types.push('complete_transfer');\n } else {\n types.push('partial_transfer');\n }\n\n // Add some common frame types based on patterns\n types.push('development', 'collaboration');\n\n return types;\n }\n\n private analyzeCollaborationPatterns(\n handoffs: HandoffProgress[]\n ): Array<{ sourceUser: string; targetUser: string; count: number }> {\n const collaborationCount = new Map<string, number>();\n\n for (const handoff of handoffs) {\n // Extract collaboration pattern from handoff data\n // Note: This is simplified - we'd need to track actual source/target users\n const pattern = this.extractCollaborationPattern(handoff);\n if (pattern) {\n const key = `${pattern.sourceUser}->${pattern.targetUser}`;\n collaborationCount.set(key, (collaborationCount.get(key) || 0) + 1);\n }\n }\n\n return Array.from(collaborationCount.entries())\n .map(([pattern, count]) => {\n const [sourceUser, targetUser] = pattern.split('->');\n return { sourceUser, targetUser, count };\n })\n .sort((a, b) => b.count - a.count)\n .slice(0, 20); // Top 20 collaboration patterns\n }\n\n private extractCollaborationPattern(\n handoff: HandoffProgress\n ): { sourceUser: string; targetUser: string } | null {\n // Simplified pattern extraction - in practice this would come from handoff metadata\n // For now, we'll create sample patterns based on handoff characteristics\n\n if (handoff.status === 'completed') {\n return {\n sourceUser: 'developer',\n targetUser: 'reviewer',\n };\n } else if (handoff.status === 'failed') {\n return {\n sourceUser: 'developer',\n targetUser: 'lead',\n };\n }\n\n return null;\n }\n\n /**\n * Real-time collaboration features\n */\n\n /**\n * Get real-time handoff status updates\n */\n async getHandoffStatusStream(\n requestId: string\n ): Promise<AsyncIterableIterator<HandoffProgress>> {\n const progress = this.activeHandoffs.get(requestId);\n if (!progress) {\n throw new DatabaseError(\n `Handoff request not found: ${requestId}`,\n ErrorCode.RESOURCE_NOT_FOUND\n );\n }\n\n // Simple implementation - in a real system this would use WebSockets or Server-Sent Events\n const self = this;\n return {\n async *[Symbol.asyncIterator]() {\n let lastStatus = progress.status;\n while (\n lastStatus !== 'completed' &&\n lastStatus !== 'failed' &&\n lastStatus !== 'cancelled'\n ) {\n const currentProgress = self.activeHandoffs.get(requestId);\n if (currentProgress && currentProgress.status !== lastStatus) {\n lastStatus = currentProgress.status;\n yield currentProgress;\n }\n // Simulate real-time polling\n await new Promise((resolve) => setTimeout(resolve, 1000));\n }\n },\n };\n }\n\n /**\n * Update handoff progress in real-time\n */\n async updateHandoffProgress(\n requestId: string,\n update: Partial<HandoffProgress>\n ): Promise<void> {\n let progress = this.activeHandoffs.get(requestId);\n\n // If progress doesn't exist and update includes required fields, create it\n if (\n !progress &&\n update.requestId &&\n update.status &&\n update.totalFrames !== undefined\n ) {\n progress = {\n requestId: update.requestId,\n status: update.status,\n transferredFrames: 0,\n totalFrames: update.totalFrames,\n currentStep: 'Initialized',\n errors: [],\n ...update,\n };\n } else if (!progress) {\n throw new DatabaseError(\n `Handoff request not found: ${requestId}`,\n ErrorCode.RESOURCE_NOT_FOUND\n );\n } else {\n // Update existing progress with provided fields\n progress = {\n ...progress,\n ...update,\n };\n }\n\n this.activeHandoffs.set(requestId, progress);\n\n logger.info(`Handoff progress updated: ${requestId}`, {\n status: progress.status,\n currentStep: progress.currentStep,\n transferredFrames: progress.transferredFrames,\n });\n\n // Notify stakeholders of progress update\n await this.notifyProgressUpdate(requestId, progress);\n }\n\n /**\n * Notify stakeholders of progress updates\n */\n private async notifyProgressUpdate(\n requestId: string,\n progress: HandoffProgress\n ): Promise<void> {\n const updateNotification: HandoffNotification = {\n id: `${requestId}-progress-${Date.now()}`,\n type: 'request',\n requestId,\n recipientId: 'all',\n title: 'Handoff Progress Update',\n message: `Status: ${progress.status} | Step: ${progress.currentStep} | Progress: ${progress.transferredFrames}/${progress.totalFrames} frames`,\n actionRequired: false,\n createdAt: new Date(),\n };\n\n // Distribute to all stakeholders\n const allUsers = Array.from(this.notifications.keys());\n for (const userId of allUsers) {\n const userNotifications = this.notifications.get(userId) || [];\n userNotifications.push({\n ...updateNotification,\n id: `${requestId}-progress-${userId}-${Date.now()}`,\n recipientId: userId,\n });\n this.notifications.set(userId, userNotifications);\n }\n }\n\n /**\n * Get active handoffs with real-time filtering\n */\n async getActiveHandoffsRealTime(filters?: {\n status?: HandoffProgress['status'];\n userId?: string;\n priority?: 'low' | 'medium' | 'high' | 'critical';\n }): Promise<HandoffProgress[]> {\n let handoffs = Array.from(this.activeHandoffs.values());\n\n if (filters?.status) {\n handoffs = handoffs.filter((h) => h.status === filters.status);\n }\n\n if (filters?.userId) {\n // In a real implementation, we'd have proper user tracking in handoff metadata\n // For now, filter based on requestId pattern or other heuristics\n handoffs = handoffs.filter((h) =>\n h.requestId.includes(filters.userId || '')\n );\n }\n\n if (filters?.priority) {\n // Filter by priority (this would need priority tracking in HandoffProgress)\n // For now, estimate priority based on frame count and errors\n handoffs = handoffs.filter((h) => {\n const estimatedPriority = this.estimateHandoffPriority(h);\n return estimatedPriority === filters.priority;\n });\n }\n\n return handoffs.sort((a, b) => {\n // Sort by status priority, then by creation time\n const statusPriority = {\n in_transfer: 4,\n approved: 3,\n pending_review: 2,\n completed: 1,\n failed: 1,\n cancelled: 0,\n };\n return (statusPriority[b.status] || 0) - (statusPriority[a.status] || 0);\n });\n }\n\n private estimateHandoffPriority(\n handoff: HandoffProgress\n ): 'low' | 'medium' | 'high' | 'critical' {\n if (handoff.errors.length > 2 || handoff.totalFrames > 50)\n return 'critical';\n if (handoff.errors.length > 0 || handoff.totalFrames > 20) return 'high';\n if (handoff.totalFrames > 5) return 'medium';\n return 'low';\n }\n\n /**\n * Bulk handoff operations for team collaboration\n */\n async bulkHandoffOperation(operation: {\n action: 'approve' | 'reject' | 'cancel';\n requestIds: string[];\n reviewerId: string;\n feedback?: string;\n }): Promise<{\n successful: string[];\n failed: Array<{ requestId: string; error: string }>;\n }> {\n const results = {\n successful: [],\n failed: [] as Array<{ requestId: string; error: string }>,\n };\n\n for (const requestId of operation.requestIds) {\n try {\n switch (operation.action) {\n case 'approve':\n await this.submitHandoffApproval(requestId, {\n reviewerId: operation.reviewerId,\n decision: 'approved',\n feedback: operation.feedback,\n });\n results.successful.push(requestId);\n break;\n\n case 'reject':\n await this.submitHandoffApproval(requestId, {\n reviewerId: operation.reviewerId,\n decision: 'rejected',\n feedback: operation.feedback || 'Bulk rejection',\n });\n results.successful.push(requestId);\n break;\n\n case 'cancel':\n await this.cancelHandoff(\n requestId,\n operation.feedback || 'Bulk cancellation'\n );\n results.successful.push(requestId);\n break;\n }\n } catch (error: unknown) {\n results.failed.push({\n requestId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n logger.info(`Bulk handoff operation completed`, {\n action: operation.action,\n successful: results.successful.length,\n failed: results.failed.length,\n reviewerId: operation.reviewerId,\n });\n\n return results;\n }\n\n /**\n * Enhanced notification management with cleanup\n */\n async cleanupExpiredNotifications(userId?: string): Promise<number> {\n let cleanedCount = 0;\n const now = new Date();\n\n const userIds = userId ? [userId] : Array.from(this.notifications.keys());\n\n for (const uid of userIds) {\n const userNotifications = this.notifications.get(uid) || [];\n const activeNotifications = userNotifications.filter((notification) => {\n if (notification.expiresAt && notification.expiresAt < now) {\n cleanedCount++;\n return false;\n }\n return true;\n });\n\n this.notifications.set(uid, activeNotifications);\n }\n\n if (cleanedCount > 0) {\n logger.info(`Cleaned up expired notifications`, {\n count: cleanedCount,\n userId: userId || 'all',\n });\n }\n\n return cleanedCount;\n }\n}\n"],
5
5
  "mappings": ";;;;AAWA,SAAS,cAAc;AACvB,SAAS,iBAAiB,eAAe,iBAAiB;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAkEA,MAAM,oBAAoB;AAAA,EACvB;AAAA,EACA,iBAA+C,oBAAI,IAAI;AAAA,EACvD,mBAAmD,oBAAI,IAAI;AAAA,EAC3D,gBAAoD,oBAAI,IAAI;AAAA,EAEpE,YAAY,kBAAoC;AAC9C,SAAK,mBAAmB;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,gBACJ,eACA,UACA,UACA,cACA,SACiB;AAEjB,UAAM,QAAQ,cAAc,uBAAuB;AAAA,MACjD;AAAA,MACA;AAAA,MACA,gBAAgB;AAAA,MAChB,YAAY;AAAA,MACZ,aAAa;AAAA,IACf,CAAC;AAED,QAAI;AAEF,YAAM,KAAK,iBACR,qBAAqB,EACrB;AAAA,QACC,KAAK,iBACF,qBAAqB,EACrB;AAAA,UACC,MAAM,eAAe;AAAA,UACrB;AAAA,UACA;AAAA,UACA,MAAM;AAAA,QACR;AAAA,MACJ;AAGF,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A,MACH;AAAA,IACF;AAEA,WAAO,KAAK,oCAAoC;AAAA,MAC9C,QAAQ,UAAU;AAAA,MAClB,YAAY,QAAQ,WAAW;AAAA,MAC/B,QAAQ,QAAQ,OAAO;AAAA,MACvB,YAAY,UAAU;AAAA,IACxB,CAAC;AAED,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,4BAA4B,QAAkC;AAClE,QAAI,eAAe;AACnB,UAAM,MAAM,oBAAI,KAAK;AAErB,UAAM,UAAU,SAAS,CAAC,MAAM,IAAI,MAAM,KAAK,KAAK,cAAc,KAAK,CAAC;AAExE,eAAW,OAAO,SAAS;AACzB,YAAM,oBAAoB,KAAK,cAAc,IAAI,GAAG,KAAK,CAAC;AAC1D,YAAM,sBAAsB,kBAAkB,OAAO,CAAC,iBAAiB;AACrE,YAAI,aAAa,aAAa,aAAa,YAAY,KAAK;AAC1D;AACA,iBAAO;AAAA,QACT;AACA,eAAO;AAAA,MACT,CAAC;AAED,WAAK,cAAc,IAAI,KAAK,mBAAmB;AAAA,IACjD;AAEA,QAAI,eAAe,GAAG;AACpB,aAAO,KAAK,oCAAoC;AAAA,QAC9C,OAAO;AAAA,QACP,QAAQ,UAAU;AAAA,MACpB,CAAC;AAAA,IACH;AAEA,WAAO;AAAA,EACT;AACF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,119 @@
1
+ import { fileURLToPath as __fileURLToPath } from 'url';
2
+ import { dirname as __pathDirname } from 'path';
3
+ const __filename = __fileURLToPath(import.meta.url);
4
+ const __dirname = __pathDirname(__filename);
5
+ import { logger } from "../monitoring/logger.js";
6
+ class FrameLifecycleHooksRegistry {
7
+ closeHooks = [];
8
+ createHooks = [];
9
+ /**
10
+ * Register a hook to be called when a frame is closed
11
+ * @param name - Unique name for the hook (for logging/debugging)
12
+ * @param handler - Async function to call when frame closes
13
+ * @param priority - Higher priority hooks run first (default: 0)
14
+ */
15
+ onFrameClosed(name, handler, priority = 0) {
16
+ const hook = { name, handler, priority };
17
+ this.closeHooks.push(hook);
18
+ this.closeHooks.sort((a, b) => b.priority - a.priority);
19
+ logger.debug("Registered frame close hook", { name, priority });
20
+ return () => {
21
+ this.closeHooks = this.closeHooks.filter((h) => h !== hook);
22
+ logger.debug("Unregistered frame close hook", { name });
23
+ };
24
+ }
25
+ /**
26
+ * Register a hook to be called when a frame is created
27
+ * @param name - Unique name for the hook (for logging/debugging)
28
+ * @param handler - Async function to call when frame is created
29
+ * @param priority - Higher priority hooks run first (default: 0)
30
+ */
31
+ onFrameCreated(name, handler, priority = 0) {
32
+ const hook = { name, handler, priority };
33
+ this.createHooks.push(hook);
34
+ this.createHooks.sort((a, b) => b.priority - a.priority);
35
+ logger.debug("Registered frame create hook", { name, priority });
36
+ return () => {
37
+ this.createHooks = this.createHooks.filter((h) => h !== hook);
38
+ logger.debug("Unregistered frame create hook", { name });
39
+ };
40
+ }
41
+ /**
42
+ * Trigger all close hooks (called by FrameManager)
43
+ * Hooks are fire-and-forget - errors don't affect frame closure
44
+ */
45
+ async triggerClose(data) {
46
+ if (this.closeHooks.length === 0) return;
47
+ const results = await Promise.allSettled(
48
+ this.closeHooks.map(async (hook) => {
49
+ try {
50
+ await hook.handler(data);
51
+ } catch (error) {
52
+ logger.warn(`Frame close hook "${hook.name}" failed`, {
53
+ error: error instanceof Error ? error.message : String(error),
54
+ frameId: data.frame.frame_id,
55
+ frameName: data.frame.name
56
+ });
57
+ }
58
+ })
59
+ );
60
+ const failed = results.filter((r) => r.status === "rejected").length;
61
+ if (failed > 0) {
62
+ logger.debug("Some frame close hooks failed", {
63
+ total: this.closeHooks.length,
64
+ failed,
65
+ frameId: data.frame.frame_id
66
+ });
67
+ }
68
+ }
69
+ /**
70
+ * Trigger all create hooks (called by FrameManager)
71
+ * Hooks are fire-and-forget - errors don't affect frame creation
72
+ */
73
+ async triggerCreate(frame) {
74
+ if (this.createHooks.length === 0) return;
75
+ const results = await Promise.allSettled(
76
+ this.createHooks.map(async (hook) => {
77
+ try {
78
+ await hook.handler(frame);
79
+ } catch (error) {
80
+ logger.warn(`Frame create hook "${hook.name}" failed`, {
81
+ error: error instanceof Error ? error.message : String(error),
82
+ frameId: frame.frame_id,
83
+ frameName: frame.name
84
+ });
85
+ }
86
+ })
87
+ );
88
+ const failed = results.filter((r) => r.status === "rejected").length;
89
+ if (failed > 0) {
90
+ logger.debug("Some frame create hooks failed", {
91
+ total: this.createHooks.length,
92
+ failed,
93
+ frameId: frame.frame_id
94
+ });
95
+ }
96
+ }
97
+ /**
98
+ * Get count of registered hooks (useful for testing)
99
+ */
100
+ getHookCounts() {
101
+ return {
102
+ close: this.closeHooks.length,
103
+ create: this.createHooks.length
104
+ };
105
+ }
106
+ /**
107
+ * Clear all hooks (useful for testing)
108
+ */
109
+ clearAll() {
110
+ this.closeHooks = [];
111
+ this.createHooks = [];
112
+ logger.debug("Cleared all frame lifecycle hooks");
113
+ }
114
+ }
115
+ const frameLifecycleHooks = new FrameLifecycleHooksRegistry();
116
+ export {
117
+ frameLifecycleHooks
118
+ };
119
+ //# sourceMappingURL=frame-lifecycle-hooks.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/core/context/frame-lifecycle-hooks.ts"],
4
+ "sourcesContent": ["/**\n * Frame Lifecycle Hooks\n * Allows external modules to subscribe to frame events without coupling to FrameManager\n */\n\nimport { logger } from '../monitoring/logger.js';\nimport type { Frame, Event, Anchor } from './frame-types.js';\n\n/**\n * Data passed to frame close hooks\n */\nexport interface FrameCloseData {\n frame: Frame;\n events: Event[];\n anchors: Anchor[];\n}\n\n/**\n * Hook function type for frame close events\n */\nexport type FrameCloseHook = (data: FrameCloseData) => Promise<void>;\n\n/**\n * Hook function type for frame create events\n */\nexport type FrameCreateHook = (frame: Frame) => Promise<void>;\n\n/**\n * Registered hook with metadata\n */\ninterface RegisteredHook<T> {\n name: string;\n handler: T;\n priority: number;\n}\n\n/**\n * Frame Lifecycle Hooks Registry\n * Singleton that manages all frame lifecycle hooks\n */\nclass FrameLifecycleHooksRegistry {\n private closeHooks: RegisteredHook<FrameCloseHook>[] = [];\n private createHooks: RegisteredHook<FrameCreateHook>[] = [];\n\n /**\n * Register a hook to be called when a frame is closed\n * @param name - Unique name for the hook (for logging/debugging)\n * @param handler - Async function to call when frame closes\n * @param priority - Higher priority hooks run first (default: 0)\n */\n onFrameClosed(\n name: string,\n handler: FrameCloseHook,\n priority: number = 0\n ): () => void {\n const hook: RegisteredHook<FrameCloseHook> = { name, handler, priority };\n this.closeHooks.push(hook);\n this.closeHooks.sort((a, b) => b.priority - a.priority);\n\n logger.debug('Registered frame close hook', { name, priority });\n\n // Return unregister function\n return () => {\n this.closeHooks = this.closeHooks.filter((h) => h !== hook);\n logger.debug('Unregistered frame close hook', { name });\n };\n }\n\n /**\n * Register a hook to be called when a frame is created\n * @param name - Unique name for the hook (for logging/debugging)\n * @param handler - Async function to call when frame is created\n * @param priority - Higher priority hooks run first (default: 0)\n */\n onFrameCreated(\n name: string,\n handler: FrameCreateHook,\n priority: number = 0\n ): () => void {\n const hook: RegisteredHook<FrameCreateHook> = { name, handler, priority };\n this.createHooks.push(hook);\n this.createHooks.sort((a, b) => b.priority - a.priority);\n\n logger.debug('Registered frame create hook', { name, priority });\n\n // Return unregister function\n return () => {\n this.createHooks = this.createHooks.filter((h) => h !== hook);\n logger.debug('Unregistered frame create hook', { name });\n };\n }\n\n /**\n * Trigger all close hooks (called by FrameManager)\n * Hooks are fire-and-forget - errors don't affect frame closure\n */\n async triggerClose(data: FrameCloseData): Promise<void> {\n if (this.closeHooks.length === 0) return;\n\n const results = await Promise.allSettled(\n this.closeHooks.map(async (hook) => {\n try {\n await hook.handler(data);\n } catch (error) {\n logger.warn(`Frame close hook \"${hook.name}\" failed`, {\n error: error instanceof Error ? error.message : String(error),\n frameId: data.frame.frame_id,\n frameName: data.frame.name,\n });\n }\n })\n );\n\n const failed = results.filter((r) => r.status === 'rejected').length;\n if (failed > 0) {\n logger.debug('Some frame close hooks failed', {\n total: this.closeHooks.length,\n failed,\n frameId: data.frame.frame_id,\n });\n }\n }\n\n /**\n * Trigger all create hooks (called by FrameManager)\n * Hooks are fire-and-forget - errors don't affect frame creation\n */\n async triggerCreate(frame: Frame): Promise<void> {\n if (this.createHooks.length === 0) return;\n\n const results = await Promise.allSettled(\n this.createHooks.map(async (hook) => {\n try {\n await hook.handler(frame);\n } catch (error) {\n logger.warn(`Frame create hook \"${hook.name}\" failed`, {\n error: error instanceof Error ? error.message : String(error),\n frameId: frame.frame_id,\n frameName: frame.name,\n });\n }\n })\n );\n\n const failed = results.filter((r) => r.status === 'rejected').length;\n if (failed > 0) {\n logger.debug('Some frame create hooks failed', {\n total: this.createHooks.length,\n failed,\n frameId: frame.frame_id,\n });\n }\n }\n\n /**\n * Get count of registered hooks (useful for testing)\n */\n getHookCounts(): { close: number; create: number } {\n return {\n close: this.closeHooks.length,\n create: this.createHooks.length,\n };\n }\n\n /**\n * Clear all hooks (useful for testing)\n */\n clearAll(): void {\n this.closeHooks = [];\n this.createHooks = [];\n logger.debug('Cleared all frame lifecycle hooks');\n }\n}\n\n/**\n * Singleton instance of the hooks registry\n */\nexport const frameLifecycleHooks = new FrameLifecycleHooksRegistry();\n"],
5
+ "mappings": ";;;;AAKA,SAAS,cAAc;AAmCvB,MAAM,4BAA4B;AAAA,EACxB,aAA+C,CAAC;AAAA,EAChD,cAAiD,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ1D,cACE,MACA,SACA,WAAmB,GACP;AACZ,UAAM,OAAuC,EAAE,MAAM,SAAS,SAAS;AACvE,SAAK,WAAW,KAAK,IAAI;AACzB,SAAK,WAAW,KAAK,CAAC,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;AAEtD,WAAO,MAAM,+BAA+B,EAAE,MAAM,SAAS,CAAC;AAG9D,WAAO,MAAM;AACX,WAAK,aAAa,KAAK,WAAW,OAAO,CAAC,MAAM,MAAM,IAAI;AAC1D,aAAO,M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,WAAW,EAAG;AAEnC,UAAM,UAAU,MAAM,QAAQ;AAAA,MAC5B,KAAK,YAAY,IAAI,OAAO,SAAS;AACnC,YAAI;AACF,gBAAM,KAAK,QAAQ,KAAK;AAAA,QAC1B,SAAS,OAAO;AACd,iBAAO,KAAK,sBAAsB,KAAK,IAAI,YAAY;AAAA,YACrD,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,YAC5D,SAAS,MAAM;AAAA,YACf,WAAW,MAAM;AAAA,UACnB,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,IACH;AAEA,UAAM,SAAS,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,UAAU,EAAE;AAC9D,QAAI,SAAS,GAAG;AACd,aAAO,MAAM,kCAAkC;AAAA,QAC7C,OAAO,KAAK,YAAY;AAAA,QACxB;AAAA,QACA,SAAS,MAAM;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAmD;AACjD,WAAO;AAAA,MACL,OAAO,KAAK,WAAW;AAAA,MACvB,QAAQ,KAAK,YAAY;AAAA,IAC3B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,WAAiB;AACf,SAAK,aAAa,CAAC;AACnB,SAAK,cAAc,CAAC;AACpB,WAAO,MAAM,mCAAmC;AAAA,EAClD;AACF;AAKO,MAAM,sBAAsB,IAAI,4BAA4B;",
6
+ "names": []
7
+ }
@@ -4,6 +4,7 @@ const __filename = __fileURLToPath(import.meta.url);
4
4
  const __dirname = __pathDirname(__filename);
5
5
  import { logger } from "../monitoring/logger.js";
6
6
  import { FrameError, ErrorCode } from "../errors/index.js";
7
+ import { FrameQueryMode } from "../session/index.js";
7
8
  class FrameStack {
8
9
  constructor(frameDb, projectId, runId) {
9
10
  this.frameDb = frameDb;
@@ -11,6 +12,7 @@ class FrameStack {
11
12
  this.runId = runId;
12
13
  }
13
14
  activeStack = [];
15
+ queryMode = FrameQueryMode.PROJECT_ACTIVE;
14
16
  /**
15
17
  * Initialize stack by loading active frames
16
18
  */
@@ -148,6 +150,33 @@ class FrameStack {
148
150
  this.activeStack = [];
149
151
  logger.info("Cleared frame stack", { previousDepth });
150
152
  }
153
+ /**
154
+ * Set query mode and reinitialize stack
155
+ */
156
+ setQueryMode(mode) {
157
+ this.queryMode = mode;
158
+ this.initialize().catch((error) => {
159
+ logger.warn("Failed to reinitialize stack with new query mode", {
160
+ mode,
161
+ error
162
+ });
163
+ });
164
+ }
165
+ /**
166
+ * Remove a specific frame from the stack without popping frames above it
167
+ */
168
+ removeFrame(frameId) {
169
+ const index = this.activeStack.indexOf(frameId);
170
+ if (index === -1) {
171
+ return false;
172
+ }
173
+ this.activeStack.splice(index, 1);
174
+ logger.debug("Removed frame from stack", {
175
+ frameId,
176
+ stackDepth: this.activeStack.length
177
+ });
178
+ return true;
179
+ }
151
180
  /**
152
181
  * Validate stack consistency
153
182
  */
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/core/context/frame-stack.ts"],
4
- "sourcesContent": ["/**\n * Frame Stack Management\n * Handles the call stack of active frames\n */\n\nimport { Frame, FrameContext, FrameType } from './frame-types.js';\nimport { FrameDatabase } from './frame-database.js';\nimport { logger } from '../monitoring/logger.js';\nimport { FrameError, ErrorCode } from '../errors/index.js';\n\nexport class FrameStack {\n private activeStack: string[] = [];\n\n constructor(\n private frameDb: FrameDatabase,\n private projectId: string,\n private runId: string\n ) {}\n\n /**\n * Initialize stack by loading active frames\n */\n async initialize(): Promise<void> {\n try {\n const activeFrames = this.frameDb.getFramesByProject(\n this.projectId,\n 'active'\n );\n\n // Rebuild stack from database\n this.activeStack = this.buildStackFromFrames(activeFrames);\n\n logger.info('Frame stack initialized', {\n stackDepth: this.activeStack.length,\n projectId: this.projectId,\n });\n } catch (error: unknown) {\n logger.error('Failed to initialize frame stack', {\n error: error instanceof Error ? error.message : String(error),\n projectId: this.projectId,\n runId: this.runId,\n });\n throw new FrameError(\n 'Failed to initialize frame stack',\n ErrorCode.FRAME_INIT_FAILED,\n {\n projectId: this.projectId,\n runId: this.runId,\n originalError: error instanceof Error ? error.message : String(error),\n }\n );\n }\n }\n\n /**\n * Push new frame onto stack\n */\n pushFrame(frameId: string): void {\n if (this.activeStack.includes(frameId)) {\n logger.warn('Frame already on stack', { frameId });\n return;\n }\n\n this.activeStack.push(frameId);\n\n logger.debug('Pushed frame to stack', {\n frameId,\n stackDepth: this.activeStack.length,\n });\n }\n\n /**\n * Pop frame from stack\n */\n popFrame(frameId?: string): string | undefined {\n if (this.activeStack.length === 0) {\n return undefined;\n }\n\n let poppedFrameId: string | undefined;\n\n if (frameId) {\n // Pop specific frame (and all frames above it)\n const index = this.activeStack.indexOf(frameId);\n if (index === -1) {\n logger.warn('Frame not found on stack', { frameId });\n return undefined;\n }\n\n // Remove the target frame and all frames above it\n const removed = this.activeStack.splice(index);\n poppedFrameId = removed[0];\n\n if (removed.length > 1) {\n logger.info('Popped multiple frames due to stack unwinding', {\n targetFrame: frameId,\n removedFrames: removed,\n });\n }\n } else {\n // Pop top frame\n poppedFrameId = this.activeStack.pop();\n }\n\n if (poppedFrameId) {\n logger.debug('Popped frame from stack', {\n frameId: poppedFrameId,\n stackDepth: this.activeStack.length,\n });\n }\n\n return poppedFrameId;\n }\n\n /**\n * Get current (top) frame ID\n */\n getCurrentFrameId(): string | undefined {\n return this.activeStack[this.activeStack.length - 1];\n }\n\n /**\n * Get stack depth\n */\n getDepth(): number {\n return this.activeStack.length;\n }\n\n /**\n * Get complete stack\n */\n getStack(): string[] {\n return [...this.activeStack];\n }\n\n /**\n * Get stack as frame objects\n */\n getStackFrames(): Frame[] {\n return this.activeStack\n .map((frameId: any) => this.frameDb.getFrame(frameId))\n .filter(Boolean) as Frame[];\n }\n\n /**\n * Get frame context for the hot stack\n */\n getHotStackContext(maxEvents: number = 20): FrameContext[] {\n return this.activeStack\n .map((frameId: any) => this.buildFrameContext(frameId, maxEvents))\n .filter(Boolean) as FrameContext[];\n }\n\n /**\n * Check if frame is on stack\n */\n isFrameActive(frameId: string): boolean {\n return this.activeStack.includes(frameId);\n }\n\n /**\n * Get parent frame ID for current frame\n */\n getParentFrameId(): string | undefined {\n if (this.activeStack.length < 2) {\n return undefined;\n }\n return this.activeStack[this.activeStack.length - 2];\n }\n\n /**\n * Get frame depth on stack (0-based)\n */\n getFrameStackDepth(frameId: string): number {\n return this.activeStack.indexOf(frameId);\n }\n\n /**\n * Clear entire stack\n */\n clear(): void {\n const previousDepth = this.activeStack.length;\n this.activeStack = [];\n\n logger.info('Cleared frame stack', { previousDepth });\n }\n\n /**\n * Validate stack consistency\n */\n validateStack(): { isValid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n // Check if all frames in stack exist and are active\n for (const frameId of this.activeStack) {\n const frame = this.frameDb.getFrame(frameId);\n\n if (!frame) {\n errors.push(`Frame not found in database: ${frameId}`);\n continue;\n }\n\n if (frame.state !== 'active') {\n errors.push(\n `Frame on stack is not active: ${frameId} (state: ${frame.state})`\n );\n }\n\n if (frame.project_id !== this.projectId) {\n errors.push(`Frame belongs to different project: ${frameId}`);\n }\n }\n\n // Check for parent-child consistency\n for (let i = 1; i < this.activeStack.length; i++) {\n const currentFrameId = this.activeStack[i];\n const expectedParentId = this.activeStack[i - 1];\n const currentFrame = this.frameDb.getFrame(currentFrameId);\n\n if (currentFrame?.parent_frame_id !== expectedParentId) {\n errors.push(\n `Frame parent mismatch: ${currentFrameId} parent should be ${expectedParentId} but is ${currentFrame?.parent_frame_id}`\n );\n }\n }\n\n return {\n isValid: errors.length === 0,\n errors,\n };\n }\n\n /**\n * Build frame context for a specific frame\n */\n private buildFrameContext(\n frameId: string,\n maxEvents: number\n ): FrameContext | null {\n try {\n const frame = this.frameDb.getFrame(frameId);\n if (!frame) {\n logger.warn('Frame not found for context building', { frameId });\n return null;\n }\n\n const anchors = this.frameDb.getFrameAnchors(frameId);\n const recentEvents = this.frameDb.getFrameEvents(frameId, maxEvents);\n const activeArtifacts = this.extractActiveArtifacts(recentEvents);\n\n return {\n frameId,\n header: {\n goal: frame.name,\n constraints: this.extractConstraints(frame.inputs),\n definitions: frame.inputs.definitions,\n },\n anchors,\n recentEvents,\n activeArtifacts,\n };\n } catch (error: unknown) {\n logger.warn('Failed to build frame context', { frameId, error });\n return null;\n }\n }\n\n /**\n * Extract constraints from frame inputs\n */\n private extractConstraints(inputs: Record<string, any>): string[] {\n const constraints: string[] = [];\n\n if (inputs.constraints && Array.isArray(inputs.constraints)) {\n constraints.push(...inputs.constraints);\n }\n\n return constraints;\n }\n\n /**\n * Extract active artifacts from events\n */\n private extractActiveArtifacts(events: any[]): string[] {\n const artifacts: string[] = [];\n\n for (const event of events) {\n if (event.event_type === 'artifact' && event.payload?.path) {\n artifacts.push(event.payload.path);\n }\n }\n\n // Return unique artifacts\n return [...new Set(artifacts)];\n }\n\n /**\n * Build stack order from database frames\n */\n private buildStackFromFrames(frames: Frame[]): string[] {\n if (frames.length === 0) {\n return [];\n }\n\n // Create parent-child map\n const parentMap = new Map<string, string>();\n const frameMap = new Map<string, Frame>();\n\n for (const frame of frames) {\n frameMap.set(frame.frame_id, frame);\n if (frame.parent_frame_id) {\n parentMap.set(frame.frame_id, frame.parent_frame_id);\n }\n }\n\n // Find root frames (no parent or parent not in active set)\n const rootFrames = frames.filter(\n (f: any) => !f.parent_frame_id || !frameMap.has(f.parent_frame_id)\n );\n\n if (rootFrames.length === 0) {\n logger.warn('No root frames found in active set');\n return [];\n }\n\n if (rootFrames.length > 1) {\n logger.warn('Multiple root frames found, using most recent', {\n rootFrames: rootFrames.map((f: any) => f.frame_id),\n });\n }\n\n // Build stack from root to leaves\n const stack: string[] = [];\n let currentFrame = rootFrames.sort(\n (a, b) => a.created_at - b.created_at\n )[0];\n\n while (currentFrame) {\n stack.push(currentFrame.frame_id);\n\n // Find child frame\n const childFrame = frames.find(\n (f: any) => f.parent_frame_id === currentFrame.frame_id\n );\n if (childFrame) {\n currentFrame = child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oBAAI,IAAoB;AAC1C,UAAM,WAAW,oBAAI,IAAmB;AAExC,eAAW,SAAS,QAAQ;AAC1B,eAAS,IAAI,MAAM,UAAU,KAAK;AAClC,UAAI,MAAM,iBAAiB;AACzB,kBAAU,IAAI,MAAM,UAAU,MAAM,eAAe;AAAA,MACrD;AAAA,IACF;AAGA,UAAM,aAAa,OAAO;AAAA,MACxB,CAAC,MAAW,CAAC,EAAE,mBAAmB,CAAC,SAAS,IAAI,EAAE,eAAe;AAAA,IACnE;AAEA,QAAI,WAAW,WAAW,GAAG;AAC3B,aAAO,KAAK,oCAAoC;AAChD,aAAO,CAAC;AAAA,IACV;AAEA,QAAI,WAAW,SAAS,GAAG;AACzB,aAAO,KAAK,iDAAiD;AAAA,QAC3D,YAAY,WAAW,IAAI,CAAC,MAAW,EAAE,QAAQ;AAAA,MACnD,CAAC;AAAA,IACH;AAGA,UAAM,QAAkB,CAAC;AACzB,QAAI,eAAe,WAAW;AAAA,MAC5B,CAAC,GAAG,MAAM,EAAE,aAAa,EAAE;AAAA,IAC7B,EAAE,CAAC;AAEH,WAAO,cAAc;AACnB,YAAM,KAAK,aAAa,QAAQ;AAGhC,YAAM,aAAa,OAAO;AAAA,QACxB,CAAC,MAAW,EAAE,oBAAoB,aAAa;AAAA,MACjD;AACA,UAAI,YAAY;AACd,uBAAe;AAAA,MACjB,OAAO;AACL;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;",
4
+ "sourcesContent": ["/**\n * Frame Stack Management\n * Handles the call stack of active frames\n */\n\nimport { Frame, FrameContext, FrameType } from './frame-types.js';\nimport { FrameDatabase } from './frame-database.js';\nimport { logger } from '../monitoring/logger.js';\nimport { FrameError, ErrorCode } from '../errors/index.js';\nimport { FrameQueryMode } from '../session/index.js';\n\nexport class FrameStack {\n private activeStack: string[] = [];\n private queryMode: FrameQueryMode = FrameQueryMode.PROJECT_ACTIVE;\n\n constructor(\n private frameDb: FrameDatabase,\n private projectId: string,\n private runId: string\n ) {}\n\n /**\n * Initialize stack by loading active frames\n */\n async initialize(): Promise<void> {\n try {\n const activeFrames = this.frameDb.getFramesByProject(\n this.projectId,\n 'active'\n );\n\n // Rebuild stack from database\n this.activeStack = this.buildStackFromFrames(activeFrames);\n\n logger.info('Frame stack initialized', {\n stackDepth: this.activeStack.length,\n projectId: this.projectId,\n });\n } catch (error: unknown) {\n logger.error('Failed to initialize frame stack', {\n error: error instanceof Error ? error.message : String(error),\n projectId: this.projectId,\n runId: this.runId,\n });\n throw new FrameError(\n 'Failed to initialize frame stack',\n ErrorCode.FRAME_INIT_FAILED,\n {\n projectId: this.projectId,\n runId: this.runId,\n originalError: error instanceof Error ? error.message : String(error),\n }\n );\n }\n }\n\n /**\n * Push new frame onto stack\n */\n pushFrame(frameId: string): void {\n if (this.activeStack.includes(frameId)) {\n logger.warn('Frame already on stack', { frameId });\n return;\n }\n\n this.activeStack.push(frameId);\n\n logger.debug('Pushed frame to stack', {\n frameId,\n stackDepth: this.activeStack.length,\n });\n }\n\n /**\n * Pop frame from stack\n */\n popFrame(frameId?: string): string | undefined {\n if (this.activeStack.length === 0) {\n return undefined;\n }\n\n let poppedFrameId: string | undefined;\n\n if (frameId) {\n // Pop specific frame (and all frames above it)\n const index = this.activeStack.indexOf(frameId);\n if (index === -1) {\n logger.warn('Frame not found on stack', { frameId });\n return undefined;\n }\n\n // Remove the target frame and all frames above it\n const removed = this.activeStack.splice(index);\n poppedFrameId = removed[0];\n\n if (removed.length > 1) {\n logger.info('Popped multiple frames due to stack unwinding', {\n targetFrame: frameId,\n removedFrames: removed,\n });\n }\n } else {\n // Pop top frame\n poppedFrameId = this.activeStack.pop();\n }\n\n if (poppedFrameId) {\n logger.debug('Popped frame from stack', {\n frameId: poppedFrameId,\n stackDepth: this.activeStack.length,\n });\n }\n\n return poppedFrameId;\n }\n\n /**\n * Get current (top) frame ID\n */\n getCurrentFrameId(): string | undefined {\n return this.activeStack[this.activeStack.length - 1];\n }\n\n /**\n * Get stack depth\n */\n getDepth(): number {\n return this.activeStack.length;\n }\n\n /**\n * Get complete stack\n */\n getStack(): string[] {\n return [...this.activeStack];\n }\n\n /**\n * Get stack as frame objects\n */\n getStackFrames(): Frame[] {\n return this.activeStack\n .map((frameId: any) => this.frameDb.getFrame(frameId))\n .filter(Boolean) as Frame[];\n }\n\n /**\n * Get frame context for the hot stack\n */\n getHotStackContext(maxEvents: number = 20): FrameContext[] {\n return this.activeStack\n .map((frameId: any) => this.buildFrameContext(frameId, maxEvents))\n .filter(Boolean) as FrameContext[];\n }\n\n /**\n * Check if frame is on stack\n */\n isFrameActive(frameId: string): boolean {\n return this.activeStack.includes(frameId);\n }\n\n /**\n * Get parent frame ID for current frame\n */\n getParentFrameId(): string | undefined {\n if (this.activeStack.length < 2) {\n return undefined;\n }\n return this.activeStack[this.activeStack.length - 2];\n }\n\n /**\n * Get frame depth on stack (0-based)\n */\n getFrameStackDepth(frameId: string): number {\n return this.activeStack.indexOf(frameId);\n }\n\n /**\n * Clear entire stack\n */\n clear(): void {\n const previousDepth = this.activeStack.length;\n this.activeStack = [];\n\n logger.info('Cleared frame stack', { previousDepth });\n }\n\n /**\n * Set query mode and reinitialize stack\n */\n setQueryMode(mode: FrameQueryMode): void {\n this.queryMode = mode;\n // Reinitialize with new query mode\n this.initialize().catch((error) => {\n logger.warn('Failed to reinitialize stack with new query mode', {\n mode,\n error,\n });\n });\n }\n\n /**\n * Remove a specific frame from the stack without popping frames above it\n */\n removeFrame(frameId: string): boolean {\n const index = this.activeStack.indexOf(frameId);\n if (index === -1) {\n return false;\n }\n\n this.activeStack.splice(index, 1);\n\n logger.debug('Removed frame from stack', {\n frameId,\n stackDepth: this.activeStack.length,\n });\n\n return true;\n }\n\n /**\n * Validate stack consistency\n */\n validateStack(): { isValid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n // Check if all frames in stack exist and are active\n for (const frameId of this.activeStack) {\n const frame = this.frameDb.getFrame(frameId);\n\n if (!frame) {\n errors.push(`Frame not found in database: ${frameId}`);\n continue;\n }\n\n if (frame.state !== 'active') {\n errors.push(\n `Frame on stack is not active: ${frameId} (state: ${frame.state})`\n );\n }\n\n if (frame.project_id !== this.projectId) {\n errors.push(`Frame belongs to different project: ${frameId}`);\n }\n }\n\n // Check for parent-child consistency\n for (let i = 1; i < this.activeStack.length; i++) {\n const currentFrameId = this.activeStack[i];\n const expectedParentId = this.activeStack[i - 1];\n const currentFrame = this.frameDb.getFrame(currentFrameId);\n\n if (currentFrame?.parent_frame_id !== expectedParentId) {\n errors.push(\n `Frame parent mismatch: ${currentFrameId} parent should be ${expectedParentId} but is ${currentFrame?.parent_frame_id}`\n );\n }\n }\n\n return {\n isValid: errors.length === 0,\n errors,\n };\n }\n\n /**\n * Build frame context for a specific frame\n */\n private buildFrameContext(\n frameId: string,\n maxEvents: number\n ): FrameContext | null {\n try {\n const frame = this.frameDb.getFrame(frameId);\n if (!frame) {\n logger.warn('Frame not found for context building', { frameId });\n return null;\n }\n\n const anchors = this.frameDb.getFrameAnchors(frameId);\n const recentEvents = this.frameDb.getFrameEvents(frameId, maxEvents);\n const activeArtifacts = this.extractActiveArtifacts(recentEvents);\n\n return {\n frameId,\n header: {\n goal: frame.name,\n constraints: this.extractConstraints(frame.inputs),\n definitions: frame.inputs.definitions,\n },\n anchors,\n recentEvents,\n activeArtifacts,\n };\n } catch (error: unknown) {\n logger.warn('Failed to build frame context', { frameId, error });\n return null;\n }\n }\n\n /**\n * Extract constraints from frame inputs\n */\n private extractConstraints(inputs: Record<string, any>): string[] {\n const constraints: string[] = [];\n\n if (inputs.constraints && Array.isArray(inputs.constraints)) {\n constraints.push(...inputs.constraints);\n }\n\n return constraints;\n }\n\n /**\n * Extract active artifacts from events\n */\n private extractActiveArtifacts(events: any[]): string[] {\n const artifacts: string[] = [];\n\n for (const event of events) {\n if (event.event_type === 'artifact' && event.payload?.path) {\n artifacts.push(event.payload.path);\n }\n }\n\n // Return unique artifacts\n return [...new Set(artifacts)];\n }\n\n /**\n * Build stack order from database frames\n */\n private buildStackFromFrames(frames: Frame[]): string[] {\n if (frames.length === 0) {\n return [];\n }\n\n // Create parent-child map\n const parentMap = new Map<string, string>();\n const frameMap = new Map<string, Frame>();\n\n for (const frame of frames) {\n frameMap.set(frame.frame_id, frame);\n if (frame.parent_frame_id) {\n parentMap.set(frame.frame_id, frame.parent_frame_id);\n }\n }\n\n // Find root frames (no parent or parent not in active set)\n const rootFrames = frames.filter(\n (f: any) => !f.parent_frame_id || !frameMap.has(f.parent_frame_id)\n );\n\n if (rootFrames.length === 0) {\n logger.warn('No root frames found in active set');\n return [];\n }\n\n if (rootFrames.length > 1) {\n logger.warn('Multiple root frames found, using most recent', {\n rootFrames: rootFrames.map((f: any) => f.frame_id),\n });\n }\n\n // Build stack from root to leaves\n const stack: string[] = [];\n let currentFrame = rootFrames.sort(\n (a, b) => a.created_at - b.created_at\n )[0];\n\n while (currentFrame) {\n stack.push(currentFrame.frame_id);\n\n // Find child frame\n const childFrame = frames.find(\n (f: any) => f.parent_frame_id === currentFrame.frame_id\n );\n if (childFrame) {\n currentFrame = childFrame;\n } else {\n break;\n }\n }\n\n return stack;\n }\n}\n"],
5
+ "mappings": ";;;;AAOA,SAAS,cAAc;AACvB,SAAS,YAAY,iBAAiB;AACtC,SAAS,sBAAsB;AAExB,MAAM,WAAW;AAAA,EAItB,YACU,SACA,WACA,OACR;AAHQ;AACA;AACA;AAAA,EACP;AAAA,EAPK,cAAwB,CAAC;AAAA,EACzB,YAA4B,eAAe;AAAA;AAAA;AAAA;AAAA,EAWnD,MAAM,aAA4B;AAChC,QAAI;AACF,YAAM,eAAe,KAAK,QAAQ;AAAA,QAChC,KAAK;AAAA,QACL;AAAA,MACF;AAGA,WAAK,cAAc,KAAK,qBAAqB,YAAY;AAEzD,aAAO,KAAK,2BAA2B;AAAA,QACrC,YAAY,KAAK,YAAY;AAAA,QAC7B,WAAW,KAAK;AAAA,MAClB,CAAC;AAAA,IACH,SAAS,OAAgB;AACvB,aAAO,MAAM,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AAI,IAAmB;AAExC,eAAW,SAAS,QAAQ;AAC1B,eAAS,IAAI,MAAM,UAAU,KAAK;AAClC,UAAI,MAAM,iBAAiB;AACzB,kBAAU,IAAI,MAAM,UAAU,MAAM,eAAe;AAAA,MACrD;AAAA,IACF;AAGA,UAAM,aAAa,OAAO;AAAA,MACxB,CAAC,MAAW,CAAC,EAAE,mBAAmB,CAAC,SAAS,IAAI,EAAE,eAAe;AAAA,IACnE;AAEA,QAAI,WAAW,WAAW,GAAG;AAC3B,aAAO,KAAK,oCAAoC;AAChD,aAAO,CAAC;AAAA,IACV;AAEA,QAAI,WAAW,SAAS,GAAG;AACzB,aAAO,KAAK,iDAAiD;AAAA,QAC3D,YAAY,WAAW,IAAI,CAAC,MAAW,EAAE,QAAQ;AAAA,MACnD,CAAC;AAAA,IACH;AAGA,UAAM,QAAkB,CAAC;AACzB,QAAI,eAAe,WAAW;AAAA,MAC5B,CAAC,GAAG,MAAM,EAAE,aAAa,EAAE;AAAA,IAC7B,EAAE,CAAC;AAEH,WAAO,cAAc;AACnB,YAAM,KAAK,aAAa,QAAQ;AAGhC,YAAM,aAAa,OAAO;AAAA,QACxB,CAAC,MAAW,EAAE,oBAAoB,aAAa;AAAA,MACjD;AACA,UAAI,YAAY;AACd,uBAAe;AAAA,MACjB,OAAO;AACL;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/core/context/incremental-gc.ts"],
4
- "sourcesContent": ["/**\n * Incremental Garbage Collection System (STA-288)\n *\n * Implements incremental GC strategy to avoid stop-the-world pauses\n * with generational aging and priority-based collection.\n */\n\nimport { Frame, FrameManager } from './frame-manager.js';\nimport { Logger } from '../monitoring/logger.js';\n\ninterface GCConfig {\n framesPerCycle: number; // Process in chunks (default: 100)\n cycleInterval: number; // Every minute (default: 60s)\n maxAge: number; // Max age before eligible for collection (30 days)\n generations: {\n young: number; // < 1 day\n mature: number; // 1-7 days\n old: number; // 7-30 days\n };\n}\n\ninterface GCStats {\n totalFrames: number;\n collectedFrames: number;\n lastRunTime: number;\n cycleCount: number;\n avgCycleTime: number;\n protectedFrames: number;\n}\n\nexport class IncrementalGarbageCollector {\n private logger: Logger;\n private config: GCConfig;\n private stats: GCStats;\n private isRunning: boolean = false;\n private cycleTimer: NodeJS.Timer | null = null;\n private frameManager: FrameManager;\n\n constructor(frameManager: FrameManager, config: Partial<GCConfig> = {}) {\n this.frameManager = frameManager;\n this.logger = new Logger('IncrementalGC');\n\n this.config = {\n framesPerCycle: config.framesPerCycle || 100,\n cycleInterval: config.cycleInterval || 60000, // 60 seconds\n maxAge: config.maxAge || 30 * 24 * 60 * 60 * 1000, // 30 days\n generations: {\n young: config.generations?.young || 24 * 60 * 60 * 1000, // 1 day\n mature: config.generations?.mature || 7 * 24 * 60 * 60 * 1000, // 7 days\n old: config.generations?.old || 30 * 24 * 60 * 60 * 1000, // 30 days\n },\n };\n\n this.stats = {\n totalFrames: 0,\n collectedFrames: 0,\n lastRunTime: 0,\n cycleCount: 0,\n avgCycleTime: 0,\n protectedFrames: 0,\n };\n\n this.logger.info('Incremental GC initialized', this.config);\n }\n\n /**\n * Start the garbage collection cycle\n */\n start(): void {\n if (this.isRunning) {\n this.logger.warn('GC already running');\n return;\n }\n\n this.isRunning = true;\n this.logger.info(\n `Starting incremental GC with ${this.config.cycleInterval}ms intervals`\n );\n\n this.cycleTimer = setInterval(() => {\n this.runCycle().catch((error) => {\n this.logger.error('GC cycle failed', error);\n });\n }, this.config.cycleInterval);\n }\n\n /**\n * Stop the garbage collection cycle\n */\n stop(): void {\n if (this.cycleTimer) {\n clearInterval(this.cycleTimer);\n this.cycleTimer = null;\n }\n this.isRunning = false;\n this.logger.info('Incremental GC stopped');\n }\n\n /**\n * Run a single GC cycle\n */\n async runCycle(): Promise<void> {\n const startTime = Date.now();\n this.logger.debug('Starting GC cycle', {\n cycle: this.stats.cycleCount + 1,\n });\n\n try {\n // Get all frames for analysis\n const allFrames = await this.frameManager.getAllFrames();\n this.stats.totalFrames = allFrames.length;\n\n if (allFrames.length === 0) {\n this.logger.debug('No frames to collect');\n return;\n }\n\n // Categorize frames by generation and protection status\n const categorized = this.categorizeFrames(allFrames);\n\n // Select candidates for collection (prioritized)\n const candidates = this.selectCollectionCandidates(categorized);\n\n // Process in chunks to avoid blocking\n const collected = await this.collectFramesIncremental(candidates);\n\n // Update statistics\n this.updateStats(startTime, collected.length);\n\n this.logger.info('GC cycle completed', {\n cycle: this.stats.cycleCount,\n collected: collected.length,\n protected: this.stats.protectedFrames,\n duration: Date.now() - startTime,\n });\n } catch (error: unknown) {\n this.logger.error('GC cycle error', error);\n }\n }\n\n /**\n * Categorize frames by generation and protection status\n */\n private categorizeFrames(frames: Frame[]): {\n young: Frame[];\n mature: Frame[];\n old: Frame[];\n protected: Frame[];\n } {\n const now = Date.now();\n const categories = { young: [], mature: [], old: [], protected: [] };\n\n for (const frame of frames) {\n const age = now - frame.created_at;\n\n // Check if frame is protected\n if (this.isProtected(frame)) {\n categories.protected.push(frame);\n continue;\n }\n\n // Categorize by age\n if (age < this.config.generations.young) {\n categories.young.push(frame);\n } else if (age < this.config.generations.mature) {\n categories.mature.push(frame);\n } else {\n categories.old.push(frame);\n }\n }\n\n this.stats.protectedFrames = categories.protected.length;\n\n this.logger.debug('Frame categorization', {\n young: categories.young.length,\n mature: categories.mature.length,\n old: categories.old.length,\n protected: categories.protected.length,\n });\n\n return categories;\n }\n\n /**\n * Check if a frame should be protected from collection\n */\n private isProtected(frame: Frame): boolean {\n // Protect current session/run frames\n const currentRunId = this.frameManager.getCurrentRunId?.();\n if (frame.run_id === currentRunId) {\n return true;\n }\n\n // Protect active frames\n if (frame.state === 'active') {\n return true;\n }\n\n // Protect recent frames (< 1 hour old)\n const recentThreshold = Date.now() - 60 * 60 * 1000; // 1 hour\n if (frame.created_at > recentThreshold) {\n return true;\n }\n\n // Protect frames with important outputs\n if (frame.outputs && Object.keys(frame.outputs).length > 0) {\n return true;\n }\n\n // Protect parent frames (have children)\n if (frame.depth === 0) {\n // Root frames\n return true;\n }\n\n return false;\n }\n\n /**\n * Select collection candidates with priority ordering\n */\n private selectCollectionCandidates(categorized: any): Frame[] {\n const candidates: Frame[] = [];\n\n // Priority 1: Closed frames without outputs\n const emptyClosedFrames = categorized.old.filter(\n (f: Frame) =>\n f.state === 'closed' &&\n (!f.outputs || Object.keys(f.outputs).length === 0)\n );\n\n // Priority 2: Orphaned frames (no dependencies)\n const orphaned = [...categorized.mature, ...categorized.old].filter(\n (f: Frame) => this.isOrphaned(f)\n );\n\n // Priority 3: Duplicate traces\n const duplicates = this.findDuplicateTraces([\n ...categorized.mature,\n ...categorized.old,\n ]);\n\n // Priority 4: Old mature frames\n const oldMature = categorized.mature.filter((f: Frame) => {\n const age = Date.now() - f.created_at;\n return age > this.config.generations.mature * 0.8; // 80% of mature threshold\n });\n\n // Combine with priority ordering\n candidates.push(...emptyClosedFrames);\n candidates.push(...orphaned);\n candidates.push(...duplicates);\n candidates.push(...oldMature);\n\n // Remove duplicates and limit to cycle size\n const uniqueCandidates = Array.from(new Set(candidates));\n return uniqueCandidates.slice(0, this.config.framesPerCycle);\n }\n\n /**\n * Check if frame is orphaned (no dependencies)\n */\n private isOrphaned(frame: Frame): boolean {\n // Check if frame has any references from other frames\n // This is a simplified check - in practice, would analyze actual dependencies\n return (\n !frame.parent_frame_id && frame.depth > 0 && frame.state === 'closed'\n );\n }\n\n /**\n * Find duplicate trace signatures\n */\n private findDuplicateTraces(frames: Frame[]): Frame[] {\n const signatureMap = new Map<string, Frame[]>();\n\n for (const frame of frames) {\n // Create a signature from trace content\n const signature = this.createTraceSignature(frame);\n if (!signatureMap.has(signature)) {\n signatureMap.set(signature, []);\n }\n signatureMap.get(signature)!.push(frame);\n }\n\n // Return duplicates (keep newest, mark older for collection)\n const duplicates: Frame[] = [];\n for (const [signature, frameList] of signatureMap) {\n if (frameList.length > 1) {\n // Sort by timestamp, keep newest\n frameList.sort((a, b) => b.timestamp - a.timestamp);\n duplicates.push(...frameList.slice(1)); // Mark older ones for collection\n }\n }\n\n return duplicates;\n }\n\n /**\n * Create a signature for duplicate detection\n */\n private createTraceSignature(frame: Frame): string {\n // Create signature from key frame properties\n const type = frame.type;\n const name = frame.name;\n const outputs = JSON.stringify(frame.outputs || {});\n const digestText = frame.digest_text || '';\n return `${type}:${name}:${outputs}:${digestText}`.toLowerCase();\n }\n\n /**\n * Collect frames incrementally to avoid blocking\n */\n private async collectFramesIncremental(\n candidates: Frame[]\n ): Promise<Frame[]> {\n const collected: Frame[] = [];\n const chunkSize = Math.min(10, Math.ceil(candidates.length / 10)); // Process in small chunks\n\n for (let i = 0; i < candidates.length; i += chunkSize) {\n const chunk = candidates.slice(i, i + chunkSize);\n\n for (const frame of chunk) {\n try {\n await this.frameManager.deleteFrame(frame.frame_id);\n collected.push(frame);\n\n this.logger.debug(`Collected frame ${frame.frame_id}`, {\n age: Date.now() - frame.created_at,\n type: frame.type,\n reason: this.getCollectionReason(frame),\n });\n } catch (error: unknown) {\n this.logger.warn(`Failed to collect frame ${frame.frame_id}`, error);\n }\n }\n\n // Yield control to avoid blocking\n await new Promise((resolve) => setImmediate(resolve));\n }\n\n return collected;\n }\n\n /**\n * Get human-readable collection reason\n */\n private getCollectionReason(frame: Frame): string {\n const age = Date.now() - frame.created_at;\n const ageHours = Math.floor(age / (60 * 60 * 1000));\n\n if (\n frame.state === 'closed' &&\n (!frame.outputs || Object.keys(frame.outputs).length === 0)\n ) {\n return 'empty-closed';\n }\n if (this.isOrphaned(frame)) return 'orphaned';\n if (ageHours > 24 * 30) return `old (${ageHours}h)`;\n return 'duplicate';\n }\n\n /**\n * Update GC statistics\n */\n private updateStats(startTime: number, collectedCount: number): void {\n const cycleTime = Date.now() - startTime;\n\n this.stats.cycleCount++;\n this.stats.collectedFrames += collectedCount;\n this.stats.lastRunTime = startTime;\n this.stats.avgCycleTime =\n (this.stats.avgCycleTime * (this.stats.cycleCount - 1) + cycleTime) /\n this.stats.cycleCount;\n }\n\n /**\n * Get GC statistics\n */\n getStats(): GCStats {\n return { ...this.stats };\n }\n\n /**\n * Force a manual GC cycle\n */\n async forceCollection(): Promise<void> {\n this.logger.info('Forcing manual GC cycle');\n await this.runCycle();\n }\n\n /**\n * Update GC configuration\n */\n updateConfig(newConfig: Partial<GCConfig>): void {\n this.config = { ...this.config, ...newConfig };\n this.logger.info('GC configuration updated', this.config);\n\n // Restart with new interval if running\n if (this.isRunning && newConfig.cycleInterval) {\n this.stop();\n this.start();\n }\n }\n}\n"],
5
- "mappings": ";;;;AAQA,SAAS,cAAc;AAsBhB,MAAM,4BAA4B;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAqB;AAAA,EACrB,aAAkC;AAAA,EAClC;AAAA,EAER,YAAY,cAA4B,SAA4B,CAAC,GAAG;AACtE,SAAK,eAAe;AACpB,SAAK,SAAS,IAAI,OAAO,eAAe;AAExC,SAAK,SAAS;AAAA,MACZ,gBAAgB,OAAO,kBAAkB;AAAA,MACzC,eAAe,OAAO,iBAAiB;AAAA;AAAA,MACvC,QAAQ,OAAO,UAAU,KAAK,KAAK,KAAK,KAAK;AAAA;AAAA,MAC7C,aAAa;AAAA,QACX,OAAO,OAAO,aAAa,SAAS,KAAK,KAAK,KAAK;AAAA;AAAA,QACnD,QAAQ,OAAO,aAAa,UAAU,IAAI,KAAK,KAAK,KAAK;AAAA;AAAA,QACzD,KAAK,OAAO,aAAa,OAAO,KAAK,KAAK,KAAK,KAAK;AAAA;AAAA,MACtD;AAAA,IACF;AAEA,SAAK,QAAQ;AAAA,MACX,aAAa;AAAA,MACb,iBAAiB;AAAA,MACjB,aAAa;AAAA,MACb,YAAY;AAAA,MACZ,cAAc;AAAA,MACd,iBAAiB;AAAA,IACnB;AAEA,SAAK,OAAO,KAAK,8BAA8B,KAAK,MAAM;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA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y to avoid stop-the-world pauses\n * with generational aging and priority-based collection.\n */\n\nimport { FrameManager } from './index.js';\nimport type { Frame } from './index.js';\nimport { Logger } from '../monitoring/logger.js';\n\ninterface GCConfig {\n framesPerCycle: number; // Process in chunks (default: 100)\n cycleInterval: number; // Every minute (default: 60s)\n maxAge: number; // Max age before eligible for collection (30 days)\n generations: {\n young: number; // < 1 day\n mature: number; // 1-7 days\n old: number; // 7-30 days\n };\n}\n\ninterface GCStats {\n totalFrames: number;\n collectedFrames: number;\n lastRunTime: number;\n cycleCount: number;\n avgCycleTime: number;\n protectedFrames: number;\n}\n\nexport class IncrementalGarbageCollector {\n private logger: Logger;\n private config: GCConfig;\n private stats: GCStats;\n private isRunning: boolean = false;\n private cycleTimer: NodeJS.Timer | null = null;\n private frameManager: FrameManager;\n\n constructor(frameManager: FrameManager, config: Partial<GCConfig> = {}) {\n this.frameManager = frameManager;\n this.logger = new Logger('IncrementalGC');\n\n this.config = {\n framesPerCycle: config.framesPerCycle || 100,\n cycleInterval: config.cycleInterval || 60000, // 60 seconds\n maxAge: config.maxAge || 30 * 24 * 60 * 60 * 1000, // 30 days\n generations: {\n young: config.generations?.young || 24 * 60 * 60 * 1000, // 1 day\n mature: config.generations?.mature || 7 * 24 * 60 * 60 * 1000, // 7 days\n old: config.generations?.old || 30 * 24 * 60 * 60 * 1000, // 30 days\n },\n };\n\n this.stats = {\n totalFrames: 0,\n collectedFrames: 0,\n lastRunTime: 0,\n cycleCount: 0,\n avgCycleTime: 0,\n protectedFrames: 0,\n };\n\n this.logger.info('Incremental GC initialized', this.config);\n }\n\n /**\n * Start the garbage collection cycle\n */\n start(): void {\n if (this.isRunning) {\n this.logger.warn('GC already running');\n return;\n }\n\n this.isRunning = true;\n this.logger.info(\n `Starting incremental GC with ${this.config.cycleInterval}ms intervals`\n );\n\n this.cycleTimer = setInterval(() => {\n this.runCycle().catch((error) => {\n this.logger.error('GC cycle failed', error);\n });\n }, this.config.cycleInterval);\n }\n\n /**\n * Stop the garbage collection cycle\n */\n stop(): void {\n if (this.cycleTimer) {\n clearInterval(this.cycleTimer);\n this.cycleTimer = null;\n }\n this.isRunning = false;\n this.logger.info('Incremental GC stopped');\n }\n\n /**\n * Run a single GC cycle\n */\n async runCycle(): Promise<void> {\n const startTime = Date.now();\n this.logger.debug('Starting GC cycle', {\n cycle: this.stats.cycleCount + 1,\n });\n\n try {\n // Get all frames for analysis\n const allFrames = await this.frameManager.getAllFrames();\n this.stats.totalFrames = allFrames.length;\n\n if (allFrames.length === 0) {\n this.logger.debug('No frames to collect');\n return;\n }\n\n // Categorize frames by generation and protection status\n const categorized = this.categorizeFrames(allFrames);\n\n // Select candidates for collection (prioritized)\n const candidates = this.selectCollectionCandidates(categorized);\n\n // Process in chunks to avoid blocking\n const collected = await this.collectFramesIncremental(candidates);\n\n // Update statistics\n this.updateStats(startTime, collected.length);\n\n this.logger.info('GC cycle completed', {\n cycle: this.stats.cycleCount,\n collected: collected.length,\n protected: this.stats.protectedFrames,\n duration: Date.now() - startTime,\n });\n } catch (error: unknown) {\n this.logger.error('GC cycle error', error);\n }\n }\n\n /**\n * Categorize frames by generation and protection status\n */\n private categorizeFrames(frames: Frame[]): {\n young: Frame[];\n mature: Frame[];\n old: Frame[];\n protected: Frame[];\n } {\n const now = Date.now();\n const categories = { young: [], mature: [], old: [], protected: [] };\n\n for (const frame of frames) {\n const age = now - frame.created_at;\n\n // Check if frame is protected\n if (this.isProtected(frame)) {\n categories.protected.push(frame);\n continue;\n }\n\n // Categorize by age\n if (age < this.config.generations.young) {\n categories.young.push(frame);\n } else if (age < this.config.generations.mature) {\n categories.mature.push(frame);\n } else {\n categories.old.push(frame);\n }\n }\n\n this.stats.protectedFrames = categories.protected.length;\n\n this.logger.debug('Frame categorization', {\n young: categories.young.length,\n mature: categories.mature.length,\n old: categories.old.length,\n protected: categories.protected.length,\n });\n\n return categories;\n }\n\n /**\n * Check if a frame should be protected from collection\n */\n private isProtected(frame: Frame): boolean {\n // Protect current session/run frames\n const currentRunId = this.frameManager.getCurrentRunId?.();\n if (frame.run_id === currentRunId) {\n return true;\n }\n\n // Protect active frames\n if (frame.state === 'active') {\n return true;\n }\n\n // Protect recent frames (< 1 hour old)\n const recentThreshold = Date.now() - 60 * 60 * 1000; // 1 hour\n if (frame.created_at > recentThreshold) {\n return true;\n }\n\n // Protect frames with important outputs\n if (frame.outputs && Object.keys(frame.outputs).length > 0) {\n return true;\n }\n\n // Protect parent frames (have children)\n if (frame.depth === 0) {\n // Root frames\n return true;\n }\n\n return false;\n }\n\n /**\n * Select collection candidates with priority ordering\n */\n private selectCollectionCandidates(categorized: any): Frame[] {\n const candidates: Frame[] = [];\n\n // Priority 1: Closed frames without outputs\n const emptyClosedFrames = categorized.old.filter(\n (f: Frame) =>\n f.state === 'closed' &&\n (!f.outputs || Object.keys(f.outputs).length === 0)\n );\n\n // Priority 2: Orphaned frames (no dependencies)\n const orphaned = [...categorized.mature, ...categorized.old].filter(\n (f: Frame) => this.isOrphaned(f)\n );\n\n // Priority 3: Duplicate traces\n const duplicates = this.findDuplicateTraces([\n ...categorized.mature,\n ...categorized.old,\n ]);\n\n // Priority 4: Old mature frames\n const oldMature = categorized.mature.filter((f: Frame) => {\n const age = Date.now() - f.created_at;\n return age > this.config.generations.mature * 0.8; // 80% of mature threshold\n });\n\n // Combine with priority ordering\n candidates.push(...emptyClosedFrames);\n candidates.push(...orphaned);\n candidates.push(...duplicates);\n candidates.push(...oldMature);\n\n // Remove duplicates and limit to cycle size\n const uniqueCandidates = Array.from(new Set(candidates));\n return uniqueCandidates.slice(0, this.config.framesPerCycle);\n }\n\n /**\n * Check if frame is orphaned (no dependencies)\n */\n private isOrphaned(frame: Frame): boolean {\n // Check if frame has any references from other frames\n // This is a simplified check - in practice, would analyze actual dependencies\n return (\n !frame.parent_frame_id && frame.depth > 0 && frame.state === 'closed'\n );\n }\n\n /**\n * Find duplicate trace signatures\n */\n private findDuplicateTraces(frames: Frame[]): Frame[] {\n const signatureMap = new Map<string, Frame[]>();\n\n for (const frame of frames) {\n // Create a signature from trace content\n const signature = this.createTraceSignature(frame);\n if (!signatureMap.has(signature)) {\n signatureMap.set(signature, []);\n }\n signatureMap.get(signature)!.push(frame);\n }\n\n // Return duplicates (keep newest, mark older for collection)\n const duplicates: Frame[] = [];\n for (const [signature, frameList] of signatureMap) {\n if (frameList.length > 1) {\n // Sort by timestamp, keep newest\n frameList.sort((a, b) => b.timestamp - a.timestamp);\n duplicates.push(...frameList.slice(1)); // Mark older ones for collection\n }\n }\n\n return duplicates;\n }\n\n /**\n * Create a signature for duplicate detection\n */\n private createTraceSignature(frame: Frame): string {\n // Create signature from key frame properties\n const type = frame.type;\n const name = frame.name;\n const outputs = JSON.stringify(frame.outputs || {});\n const digestText = frame.digest_text || '';\n return `${type}:${name}:${outputs}:${digestText}`.toLowerCase();\n }\n\n /**\n * Collect frames incrementally to avoid blocking\n */\n private async collectFramesIncremental(\n candidates: Frame[]\n ): Promise<Frame[]> {\n const collected: Frame[] = [];\n const chunkSize = Math.min(10, Math.ceil(candidates.length / 10)); // Process in small chunks\n\n for (let i = 0; i < candidates.length; i += chunkSize) {\n const chunk = candidates.slice(i, i + chunkSize);\n\n for (const frame of chunk) {\n try {\n await this.frameManager.deleteFrame(frame.frame_id);\n collected.push(frame);\n\n this.logger.debug(`Collected frame ${frame.frame_id}`, {\n age: Date.now() - frame.created_at,\n type: frame.type,\n reason: this.getCollectionReason(frame),\n });\n } catch (error: unknown) {\n this.logger.warn(`Failed to collect frame ${frame.frame_id}`, error);\n }\n }\n\n // Yield control to avoid blocking\n await new Promise((resolve) => setImmediate(resolve));\n }\n\n return collected;\n }\n\n /**\n * Get human-readable collection reason\n */\n private getCollectionReason(frame: Frame): string {\n const age = Date.now() - frame.created_at;\n const ageHours = Math.floor(age / (60 * 60 * 1000));\n\n if (\n frame.state === 'closed' &&\n (!frame.outputs || Object.keys(frame.outputs).length === 0)\n ) {\n return 'empty-closed';\n }\n if (this.isOrphaned(frame)) return 'orphaned';\n if (ageHours > 24 * 30) return `old (${ageHours}h)`;\n return 'duplicate';\n }\n\n /**\n * Update GC statistics\n */\n private updateStats(startTime: number, collectedCount: number): void {\n const cycleTime = Date.now() - startTime;\n\n this.stats.cycleCount++;\n this.stats.collectedFrames += collectedCount;\n this.stats.lastRunTime = startTime;\n this.stats.avgCycleTime =\n (this.stats.avgCycleTime * (this.stats.cycleCount - 1) + cycleTime) /\n this.stats.cycleCount;\n }\n\n /**\n * Get GC statistics\n */\n getStats(): GCStats {\n return { ...this.stats };\n }\n\n /**\n * Force a manual GC cycle\n */\n async forceCollection(): Promise<void> {\n this.logger.info('Forcing manual GC cycle');\n await this.runCycle();\n }\n\n /**\n * Update GC configuration\n */\n updateConfig(newConfig: Partial<GCConfig>): void {\n this.config = { ...this.config, ...newConfig };\n this.logger.info('GC configuration updated', this.config);\n\n // Restart with new interval if running\n if (this.isRunning && newConfig.cycleInterval) {\n this.stop();\n this.start();\n }\n }\n}\n"],
5
+ "mappings": ";;;;AASA,SAAS,cAAc;AAsBhB,MAAM,4BAA4B;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAqB;AAAA,EACrB,aAAkC;AAAA,EAClC;AAAA,EAER,YAAY,cAA4B,SAA4B,CAAC,GAAG;AACtE,SAAK,eAAe;AACpB,SAAK,SAAS,IAAI,OAAO,eAAe;AAExC,SAAK,SAAS;AAAA,MACZ,gBAAgB,OAAO,kBAAkB;AAAA,MACzC,eAAe,OAAO,iBAAiB;AAAA;AAAA,MACvC,QAAQ,OAAO,UAAU,KAAK,KAAK,KAAK,KAAK;AAAA;AAAA,MAC7C,aAAa;AAAA,QACX,OAAO,OAAO,aAAa,SAAS,KAAK,KAAK,KAAK;AAAA;AAAA,QACnD,QAAQ,OAAO,aAAa,UAAU,IAAI,KAAK,KAAK,KAAK;AAAA;AAAA,QACzD,KAAK,OAAO,aAAa,OAAO,KAAK,KAAK,KAAK,KAAK;AAAA;AAAA,MACtD;AAAA,IACF;AAEA,S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