claude-flow 2.7.34 → 2.7.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +82 -0
- package/bin/claude-flow +1 -1
- package/dist/src/__tests__/benchmarks/performance.bench.js +0 -19
- package/dist/src/__tests__/benchmarks/performance.bench.js.map +1 -1
- package/dist/src/__tests__/hook-matchers.test.js.map +1 -1
- package/dist/src/agents/agent-registry.js.map +1 -1
- package/dist/src/api/auth-service.js.map +1 -1
- package/dist/src/api/claude-client-enhanced.js +4 -2
- package/dist/src/api/claude-client-enhanced.js.map +1 -1
- package/dist/src/api/claude-client.js +4 -2
- package/dist/src/api/claude-client.js.map +1 -1
- package/dist/src/api/database-service.js.map +1 -1
- package/dist/src/api/swarm-api.js +1 -1
- package/dist/src/api/swarm-api.js.map +1 -1
- package/dist/src/cli/commands/hive-mind/wizard.js +1 -1
- package/dist/src/cli/commands/hive-mind/wizard.js.map +1 -1
- package/dist/src/cli/help-formatter.js +0 -5
- package/dist/src/cli/init/index.js +55 -33
- package/dist/src/cli/init/index.js.map +1 -1
- package/dist/src/cli/simple-commands/init/skills-copier.js +1 -1
- package/dist/src/cli/simple-commands/init/skills-copier.js.map +1 -1
- package/dist/src/cli/simple-orchestrator.js +1 -1
- package/dist/src/cli/simple-orchestrator.js.map +1 -1
- package/dist/src/coordination/conflict-resolution.js +1 -1
- package/dist/src/coordination/conflict-resolution.js.map +1 -1
- package/dist/src/coordination/load-balancer.js +1 -1
- package/dist/src/coordination/load-balancer.js.map +1 -1
- package/dist/src/core/DatabaseManager.js +39 -9
- package/dist/src/core/DatabaseManager.js.map +1 -1
- package/dist/src/core/config.js +1 -1
- package/dist/src/core/config.js.map +1 -1
- package/dist/src/enterprise/audit-manager.js +1 -1
- package/dist/src/enterprise/audit-manager.js.map +1 -1
- package/dist/src/providers/openai-provider.js +2 -2
- package/dist/src/providers/openai-provider.js.map +1 -1
- package/dist/src/sdk/checkpoint-manager.js +1 -1
- package/dist/src/sdk/checkpoint-manager.js.map +1 -1
- package/dist/src/services/agentic-flow-hooks/workflow-hooks.js +1 -1
- package/dist/src/services/agentic-flow-hooks/workflow-hooks.js.map +1 -1
- package/dist/src/swarm/coordinator.js +1 -1
- package/dist/src/swarm/coordinator.js.map +1 -1
- package/dist/src/utils/error-recovery.js +215 -0
- package/dist/src/utils/error-recovery.js.map +1 -0
- package/dist/src/utils/key-redactor.js.map +1 -1
- package/dist/src/utils/metrics-reader.js +10 -0
- package/dist/src/verification/rollback.js +2 -2
- package/dist/src/verification/rollback.js.map +1 -1
- package/dist/src/verification/tests/mocks/false-reporting-scenarios.test.js +4 -2
- package/dist/src/verification/tests/mocks/false-reporting-scenarios.test.js.map +1 -1
- package/docs/.claude-flow/metrics/performance.json +3 -3
- package/docs/.claude-flow/metrics/task-metrics.json +3 -3
- package/docs/architecture/README.md +555 -0
- package/docs/architecture/github-workflows-optimization-strategy.md +1079 -0
- package/docs/architecture/workflow-architecture-diagram.md +615 -0
- package/docs/architecture/workflow-optimization-implementation-guide.md +593 -0
- package/docs/features/AUTOMATIC_ERROR_RECOVERY_v2.7.35.md +321 -0
- package/docs/features/automatic-error-recovery.md +333 -0
- package/docs/fixes/WORKFLOW_FIXES.md +292 -0
- package/docs/fixes/WORKFLOW_FIXES_FINAL_STATUS.md +291 -0
- package/docs/fixes/github-workflow-fixes-pr888.md +279 -0
- package/docs/fixes/workflow-fixes-action-plan.md +388 -0
- package/docs/github-issues/README.md +88 -0
- package/docs/github-issues/wsl-enotempty-automatic-recovery.md +470 -0
- package/docs/github-workflow-fixes.md +219 -0
- package/docs/reviews/github-workflows-analysis-report.md +820 -0
- package/docs/reviews/pr-888-review-report.md +560 -0
- package/docs/testing/CONFIRMATION_AUTOMATIC_ERROR_RECOVERY.md +384 -0
- package/docs/testing/DOCKER_TEST_RESULTS_v2.7.35.md +305 -0
- package/docs/troubleshooting/wsl-better-sqlite3-error.md +239 -0
- package/docs/validation/workflow-fix-verification.md +206 -0
- package/package.json +7 -7
- package/scripts/create-github-issue.sh +64 -0
- package/scripts/test-docker-wsl.sh +198 -0
- package/src/__tests__/benchmarks/performance.bench.ts +2 -25
- package/src/__tests__/hook-matchers.test.ts +2 -0
- package/src/agents/agent-registry.ts +1 -1
- package/src/api/auth-service.ts +1 -1
- package/src/api/claude-client-enhanced.ts +2 -1
- package/src/api/claude-client.ts +2 -2
- package/src/api/database-service.ts +1 -2
- package/src/api/swarm-api.ts +2 -2
- package/src/cli/commands/hive-mind/wizard.ts +1 -1
- package/src/cli/init/index.ts +72 -42
- package/src/cli/simple-commands/init/skills-copier.js +1 -1
- package/src/cli/simple-orchestrator.ts +1 -1
- package/src/coordination/conflict-resolution.ts +1 -1
- package/src/coordination/load-balancer.ts +1 -1
- package/src/core/DatabaseManager.ts +55 -9
- package/src/core/config.ts +1 -1
- package/src/enterprise/audit-manager.ts +1 -1
- package/src/providers/openai-provider.ts +2 -2
- package/src/sdk/checkpoint-manager.ts +1 -1
- package/src/services/agentic-flow-hooks/workflow-hooks.ts +1 -1
- package/src/swarm/coordinator.ts +1 -1
- package/src/utils/error-recovery.ts +325 -0
- package/src/verification/rollback.ts +2 -2
- package/src/verification/tests/mocks/false-reporting-scenarios.test.ts +6 -3
- /package/docs/{BUG_REPORT_MEMORY_STATS.md → bug-reports/BUG_REPORT_MEMORY_STATS.md} +0 -0
- /package/docs/{MCP_2025_FEATURE_CONFIRMATION.md → features/MCP_2025_FEATURE_CONFIRMATION.md} +0 -0
- /package/docs/{OPTIONAL_LOCAL_EMBEDDINGS.md → features/OPTIONAL_LOCAL_EMBEDDINGS.md} +0 -0
- /package/docs/{mcp-2025-implementation-summary.md → features/mcp-2025-implementation-summary.md} +0 -0
- /package/docs/{mcp-spec-2025-implementation-plan.md → features/mcp-spec-2025-implementation-plan.md} +0 -0
- /package/docs/{AGENTIC_FLOW_ENABLED_LOG_FIX.md → fixes/AGENTIC_FLOW_ENABLED_LOG_FIX.md} +0 -0
- /package/docs/{MEMORY_COMMAND_FIX.md → fixes/MEMORY_COMMAND_FIX.md} +0 -0
- /package/docs/{NPX_MEMORY_FIX_v2.7.19.md → fixes/NPX_MEMORY_FIX_v2.7.19.md} +0 -0
- /package/docs/{REMOTE_INSTALL_FIX.md → fixes/REMOTE_INSTALL_FIX.md} +0 -0
- /package/docs/{SQLITE_FIX_COMPLETE_v2.7.21.md → fixes/SQLITE_FIX_COMPLETE_v2.7.21.md} +0 -0
- /package/docs/{NPM_PUBLISH_GUIDE_v2.7.33.md → guides/NPM_PUBLISH_GUIDE_v2.7.33.md} +0 -0
- /package/docs/{SWARM_INITIALIZATION_GUIDE.md → guides/SWARM_INITIALIZATION_GUIDE.md} +0 -0
- /package/docs/{AGENTDB_BRANCH_MERGE_VERIFICATION.md → integration/AGENTDB_BRANCH_MERGE_VERIFICATION.md} +0 -0
- /package/docs/{INTEGRATION_STATUS_FINAL.md → integration/INTEGRATION_STATUS_FINAL.md} +0 -0
- /package/docs/{agentic-flow-agentdb-mcp-integration.md → integration/agentic-flow-agentdb-mcp-integration.md} +0 -0
- /package/docs/{phase-1-2-implementation-summary.md → integration/phase-1-2-implementation-summary.md} +0 -0
- /package/docs/{.github-release-issue-v2.7.33.md → releases/.github-release-issue-v2.7.33.md} +0 -0
- /package/docs/{RELEASE_NOTES_v2.7.15.md → releases/RELEASE_NOTES_v2.7.15.md} +0 -0
- /package/docs/{RELEASE_NOTES_v2.7.33.md → releases/RELEASE_NOTES_v2.7.33.md} +0 -0
- /package/docs/{RELEASE_READINESS_SUMMARY.md → releases/RELEASE_READINESS_SUMMARY.md} +0 -0
- /package/docs/{RELEASE_SUMMARY_v2.7.33.md → releases/RELEASE_SUMMARY_v2.7.33.md} +0 -0
- /package/docs/{V2.7.14_RELEASE_NOTES.md → releases/V2.7.14_RELEASE_NOTES.md} +0 -0
- /package/docs/{V2.7.25_RELEASE_NOTES.md → releases/V2.7.25_RELEASE_NOTES.md} +0 -0
- /package/docs/{V2.7.26_RELEASE_SUMMARY.md → releases/V2.7.26_RELEASE_SUMMARY.md} +0 -0
- /package/docs/{V2.7.27_RELEASE_NOTES.md → releases/V2.7.27_RELEASE_NOTES.md} +0 -0
- /package/docs/{V2.7.28_RELEASE_NOTES.md → releases/V2.7.28_RELEASE_NOTES.md} +0 -0
- /package/docs/{AGENTIC_FLOW_INTEGRATION_REVIEW.md → reviews/AGENTIC_FLOW_INTEGRATION_REVIEW.md} +0 -0
- /package/docs/{BRANCH_REVIEW_SUMMARY.md → reviews/BRANCH_REVIEW_SUMMARY.md} +0 -0
- /package/docs/{DEEP_CODE_REVIEW_v2.7.33.md → reviews/DEEP_CODE_REVIEW_v2.7.33.md} +0 -0
- /package/docs/{LATEST_LIBRARIES_REVIEW.md → reviews/LATEST_LIBRARIES_REVIEW.md} +0 -0
- /package/docs/{REGRESSION_TEST_REPORT_v2.7.33.md → testing/REGRESSION_TEST_REPORT_v2.7.33.md} +0 -0
- /package/docs/{V2.7.27_TEST_REPORT.md → testing/V2.7.27_TEST_REPORT.md} +0 -0
- /package/docs/{regression-analysis-phase-1-2.md → testing/regression-analysis-phase-1-2.md} +0 -0
- /package/docs/{TRANSFORMER_INITIALIZATION_ISSUE.md → troubleshooting/TRANSFORMER_INITIALIZATION_ISSUE.md} +0 -0
- /package/docs/{FIX_VERIFICATION_MEMORY_STATS.md → validation/FIX_VERIFICATION_MEMORY_STATS.md} +0 -0
- /package/docs/{TOOL_VALIDATION_REPORT.md → validation/TOOL_VALIDATION_REPORT.md} +0 -0
- /package/docs/{VALIDATION_REPORT_v2.7.1.md → validation/VALIDATION_REPORT_v2.7.1.md} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/sdk/checkpoint-manager.ts"],"sourcesContent":["/**\n * Real Checkpoint Manager - 100% SDK-Powered\n * Claude-Flow v2.5-alpha.130+\n *\n * Uses ONLY Claude Code SDK primitives - TRUE checkpointing:\n * - Message UUIDs (checkpoint IDs are message UUIDs)\n * - resumeSessionAt: messageId (SDK rewinds to checkpoint)\n * - resume: sessionId (SDK loads session history)\n *\n * VERIFIED: Git-like checkpointing using actual SDK capabilities\n */\n\nimport { query, type Query, type SDKMessage, type Options } from '@anthropic-ai/claude-code';\nimport { EventEmitter } from 'events';\nimport { promises as fs } from 'fs';\nimport { join } from 'path';\n\nexport interface Checkpoint {\n id: string; // Message UUID\n sessionId: string;\n description: string;\n timestamp: number;\n messageCount: number;\n totalTokens: number;\n filesModified: string[];\n}\n\nexport interface CheckpointManagerOptions {\n persistPath?: string;\n autoCheckpointInterval?: number; // Messages between auto-checkpoints\n maxCheckpoints?: number; // Max checkpoints to keep per session\n}\n\n/**\n * Real Checkpoint Manager using ONLY SDK features\n * Git-like checkpointing with message UUIDs\n *\n * ✅ VERIFIED: Not fake - actually creates restore points using SDK\n */\nexport class RealCheckpointManager extends EventEmitter {\n private checkpoints = new Map<string, Checkpoint>();\n private sessionMessages = new Map<string, SDKMessage[]>();\n private persistPath: string;\n private autoCheckpointInterval: number;\n private maxCheckpoints: number;\n private messageCounters = new Map<string, number>();\n\n constructor(options: CheckpointManagerOptions = {}) {\n super();\n this.persistPath = options.persistPath || '.claude-flow/checkpoints';\n this.autoCheckpointInterval = options.autoCheckpointInterval || 10; // Every 10 messages\n this.maxCheckpoints = options.maxCheckpoints || 50;\n this.ensurePersistPath();\n }\n\n private async ensurePersistPath() {\n try {\n await fs.mkdir(this.persistPath, { recursive: true });\n } catch (error) {\n // Directory exists\n }\n }\n\n /**\n * Track messages for a session\n * Call this to monitor session progress and enable auto-checkpointing\n */\n async trackSession(\n sessionId: string,\n queryGenerator: Query,\n autoCheckpoint: boolean = false\n ): Promise<void> {\n let messages = this.sessionMessages.get(sessionId) || [];\n this.sessionMessages.set(sessionId, messages);\n\n let messageCount = this.messageCounters.get(sessionId) || 0;\n\n for await (const message of queryGenerator) {\n messages.push(message);\n messageCount++;\n\n this.messageCounters.set(sessionId, messageCount);\n\n this.emit('message:tracked', {\n sessionId,\n messageCount,\n messageType: message.type,\n messageUuid: message.uuid,\n });\n\n // Auto-checkpoint if enabled\n if (autoCheckpoint && messageCount % this.autoCheckpointInterval === 0) {\n await this.createCheckpoint(\n sessionId,\n `Auto-checkpoint at ${messageCount} messages`\n );\n }\n }\n }\n\n /**\n * Create a checkpoint using message UUID\n *\n * ✅ VERIFIED: Checkpoint ID = message UUID (can rollback to this exact point)\n */\n async createCheckpoint(sessionId: string, description: string): Promise<string> {\n const messages = this.sessionMessages.get(sessionId);\n\n if (!messages || messages.length === 0) {\n throw new Error(`No messages tracked for session: ${sessionId}`);\n }\n\n const lastMessage = messages[messages.length - 1];\n const checkpointId = lastMessage.uuid; // ✅ Checkpoint = message UUID!\n\n // Calculate stats\n const totalTokens = this.calculateTotalTokens(messages);\n const filesModified = this.extractFilesModified(messages);\n\n const checkpoint: Checkpoint = {\n id: checkpointId,\n sessionId,\n description,\n timestamp: Date.now(),\n messageCount: messages.length,\n totalTokens,\n filesModified,\n };\n\n this.checkpoints.set(checkpointId, checkpoint);\n await this.persistCheckpoint(checkpoint);\n\n // Enforce max checkpoints limit\n await this.enforceCheckpointLimit(sessionId);\n\n this.emit('checkpoint:created', {\n checkpointId,\n sessionId,\n description,\n messageCount: messages.length,\n });\n\n return checkpointId;\n }\n\n /**\n * Rollback to a checkpoint\n *\n * ✅ VERIFIED: Uses SDK's resumeSessionAt to rewind to exact message UUID\n */\n async rollbackToCheckpoint(\n checkpointId: string,\n continuePrompt?: string\n ): Promise<Query> {\n const checkpoint = this.checkpoints.get(checkpointId);\n\n if (!checkpoint) {\n // Try to load from disk\n const loaded = await this.loadCheckpoint(checkpointId);\n if (!loaded) {\n throw new Error(`Checkpoint not found: ${checkpointId}`);\n }\n }\n\n const chkpt = this.checkpoints.get(checkpointId)!;\n\n // Use SDK's resumeSessionAt to rollback to checkpoint\n const rolledBackQuery = query({\n prompt: continuePrompt || 'Continue from checkpoint',\n options: {\n resume: chkpt.sessionId,\n resumeSessionAt: checkpointId, // ✅ SDK rewinds to this message UUID!\n }\n });\n\n this.emit('checkpoint:rollback', {\n checkpointId,\n sessionId: chkpt.sessionId,\n description: chkpt.description,\n });\n\n return rolledBackQuery;\n }\n\n /**\n * List checkpoints for a session\n */\n listCheckpoints(sessionId: string): Checkpoint[] {\n return Array.from(this.checkpoints.values())\n .filter(c => c.sessionId === sessionId)\n .sort((a, b) => b.timestamp - a.timestamp);\n }\n\n /**\n * Get checkpoint info\n */\n getCheckpoint(checkpointId: string): Checkpoint | undefined {\n return this.checkpoints.get(checkpointId);\n }\n\n /**\n * Delete a checkpoint\n */\n async deleteCheckpoint(checkpointId: string): Promise<void> {\n const checkpoint = this.checkpoints.get(checkpointId);\n\n if (checkpoint) {\n this.checkpoints.delete(checkpointId);\n await this.deletePersistedCheckpoint(checkpointId);\n\n this.emit('checkpoint:deleted', {\n checkpointId,\n sessionId: checkpoint.sessionId,\n });\n }\n }\n\n /**\n * Calculate diff between two checkpoints\n */\n getCheckpointDiff(fromId: string, toId: string): {\n messagesDiff: number;\n tokensDiff: number;\n filesAdded: string[];\n filesRemoved: string[];\n } {\n const from = this.checkpoints.get(fromId);\n const to = this.checkpoints.get(toId);\n\n if (!from || !to) {\n throw new Error('Checkpoint not found');\n }\n\n const fromFiles = new Set(from.filesModified);\n const toFiles = new Set(to.filesModified);\n\n const filesAdded = Array.from(toFiles).filter(f => !fromFiles.has(f));\n const filesRemoved = Array.from(fromFiles).filter(f => !toFiles.has(f));\n\n return {\n messagesDiff: to.messageCount - from.messageCount,\n tokensDiff: to.totalTokens - from.totalTokens,\n filesAdded,\n filesRemoved,\n };\n }\n\n /**\n * Calculate total tokens from messages\n */\n private calculateTotalTokens(messages: SDKMessage[]): number {\n let total = 0;\n\n for (const msg of messages) {\n if ('message' in msg && 'usage' in msg.message) {\n const usage = msg.message.usage as { input_tokens?: number; output_tokens?: number };\n total += (usage.input_tokens || 0) + (usage.output_tokens || 0);\n }\n }\n\n return total;\n }\n\n /**\n * Extract files modified from messages\n */\n private extractFilesModified(messages: SDKMessage[]): string[] {\n const files = new Set<string>();\n\n for (const msg of messages) {\n if (msg.type === 'assistant' && 'message' in msg) {\n const content = msg.message.content;\n for (const block of content) {\n if (block.type === 'tool_use') {\n // Check for file operations\n if (block.name === 'Edit' || block.name === 'Write' || block.name === 'FileEdit' || block.name === 'FileWrite') {\n const input = block.input as { file_path?: string };\n if (input.file_path) {\n files.add(input.file_path);\n }\n }\n }\n }\n }\n }\n\n return Array.from(files);\n }\n\n /**\n * Persist checkpoint to disk\n */\n private async persistCheckpoint(checkpoint: Checkpoint): Promise<void> {\n const filePath = join(this.persistPath, `${checkpoint.id}.json`);\n\n try {\n await fs.writeFile(\n filePath,\n JSON.stringify(checkpoint, null, 2),\n 'utf-8'\n );\n\n this.emit('persist:saved', {\n checkpointId: checkpoint.id,\n filePath,\n });\n } catch (error) {\n this.emit('persist:error', {\n checkpointId: checkpoint.id,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Load checkpoint from disk\n */\n private async loadCheckpoint(checkpointId: string): Promise<boolean> {\n const filePath = join(this.persistPath, `${checkpointId}.json`);\n\n try {\n const data = await fs.readFile(filePath, 'utf-8');\n const checkpoint = JSON.parse(data) as Checkpoint;\n\n this.checkpoints.set(checkpointId, checkpoint);\n this.emit('persist:loaded', { checkpointId, filePath });\n\n return true;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Delete persisted checkpoint\n */\n private async deletePersistedCheckpoint(checkpointId: string): Promise<void> {\n const filePath = join(this.persistPath, `${checkpointId}.json`);\n\n try {\n await fs.unlink(filePath);\n this.emit('persist:deleted', { checkpointId });\n } catch (error) {\n // File doesn't exist, ignore\n }\n }\n\n /**\n * Enforce max checkpoint limit per session\n */\n private async enforceCheckpointLimit(sessionId: string): Promise<void> {\n const sessionCheckpoints = this.listCheckpoints(sessionId);\n\n if (sessionCheckpoints.length > this.maxCheckpoints) {\n // Delete oldest checkpoints beyond limit\n const toDelete = sessionCheckpoints.slice(this.maxCheckpoints);\n\n for (const checkpoint of toDelete) {\n await this.deleteCheckpoint(checkpoint.id);\n }\n\n this.emit('checkpoint:limit_enforced', {\n sessionId,\n deleted: toDelete.length,\n });\n }\n }\n\n /**\n * List all persisted checkpoints (even after restart)\n */\n async listPersistedCheckpoints(): Promise<string[]> {\n try {\n const files = await fs.readdir(this.persistPath);\n return files\n .filter(f => f.endsWith('.json'))\n .map(f => f.replace('.json', ''));\n } catch (error) {\n return [];\n }\n }\n\n /**\n * Load all checkpoints from disk\n */\n async loadAllCheckpoints(): Promise<number> {\n const checkpointIds = await this.listPersistedCheckpoints();\n let loaded = 0;\n\n for (const id of checkpointIds) {\n if (await this.loadCheckpoint(id)) {\n loaded++;\n }\n }\n\n this.emit('checkpoints:loaded', { count: loaded });\n return loaded;\n }\n}\n\n// Export singleton instance\nexport const checkpointManager = new RealCheckpointManager();\n"],"names":["query","EventEmitter","promises","fs","join","RealCheckpointManager","checkpoints","Map","sessionMessages","persistPath","autoCheckpointInterval","maxCheckpoints","messageCounters","options","ensurePersistPath","mkdir","recursive","error","trackSession","sessionId","queryGenerator","autoCheckpoint","messages","get","set","messageCount","message","push","emit","messageType","type","messageUuid","uuid","createCheckpoint","description","length","Error","lastMessage","checkpointId","totalTokens","calculateTotalTokens","filesModified","extractFilesModified","checkpoint","id","timestamp","Date","now","persistCheckpoint","enforceCheckpointLimit","rollbackToCheckpoint","continuePrompt","loaded","loadCheckpoint","chkpt","rolledBackQuery","prompt","resume","resumeSessionAt","listCheckpoints","Array","from","values","filter","c","sort","a","b","getCheckpoint","deleteCheckpoint","delete","deletePersistedCheckpoint","getCheckpointDiff","fromId","toId","to","fromFiles","Set","toFiles","filesAdded","f","has","filesRemoved","messagesDiff","tokensDiff","total","msg","usage","input_tokens","output_tokens","files","content","block","name","input","file_path","add","filePath","writeFile","JSON","stringify","String","data","readFile","parse","unlink","sessionCheckpoints","toDelete","slice","deleted","listPersistedCheckpoints","readdir","endsWith","map","replace","loadAllCheckpoints","checkpointIds","count","chec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qB,IAAI,CAAC/C,eAAe,CAACxC;QAEhD,IAAIuF,mBAAmBvE,MAAM,GAAG,IAAI,CAACxB,cAAc,EAAE;YAEnD,MAAMgG,WAAWD,mBAAmBE,KAAK,CAAC,IAAI,CAACjG,cAAc;YAE7D,KAAK,MAAMgC,cAAcgE,SAAU;gBACjC,MAAM,IAAI,CAACtC,gBAAgB,CAAC1B,WAAWC,EAAE;YAC3C;YAEA,IAAI,CAAChB,IAAI,CAAC,6BAA6B;gBACrCT;gBACA0F,SAASF,SAASxE,MAAM;YAC1B;QACF;IACF;IAKA,MAAM2E,2BAA8C;QAClD,IAAI;YACF,MAAMpB,QAAQ,MAAMvF,GAAG4G,OAAO,CAAC,IAAI,CAACtG,WAAW;YAC/C,OAAOiF,MACJ3B,MAAM,CAACiB,CAAAA,IAAKA,EAAEgC,QAAQ,CAAC,UACvBC,GAAG,CAACjC,CAAAA,IAAKA,EAAEkC,OAAO,CAAC,SAAS;QACjC,EAAE,OAAOjG,OAAO;YACd,OAAO,EAAE;QACX;IACF;IAKA,MAAMkG,qBAAsC;QAC1C,MAAMC,gBAAgB,MAAM,IAAI,CAACN,wBAAwB;QACzD,IAAI1D,SAAS;QAEb,KAAK,MAAMR,MAAMwE,cAAe;YAC9B,IAAI,MAAM,IAAI,CAAC/D,cAAc,CAACT,KAAK;gBACjCQ;YACF;QACF;QAEA,IAAI,CAACxB,IAAI,CAAC,sBAAsB;YAAEyF,OAAOjE;QAAO;QAChD,OAAOA;IACT;AACF;AAGA,OAAO,MAAMkE,oBAAoB,IAAIjH,wBAAwB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/sdk/checkpoint-manager.ts"],"sourcesContent":["/**\n * Real Checkpoint Manager - 100% SDK-Powered\n * Claude-Flow v2.5-alpha.130+\n *\n * Uses ONLY Claude Code SDK primitives - TRUE checkpointing:\n * - Message UUIDs (checkpoint IDs are message UUIDs)\n * - resumeSessionAt: messageId (SDK rewinds to checkpoint)\n * - resume: sessionId (SDK loads session history)\n *\n * VERIFIED: Git-like checkpointing using actual SDK capabilities\n */\n\nimport { query, type Query, type SDKMessage, type Options } from '@anthropic-ai/claude-code';\nimport { EventEmitter } from 'events';\nimport { promises as fs } from 'fs';\nimport { join } from 'path';\n\nexport interface Checkpoint {\n id: string; // Message UUID\n sessionId: string;\n description: string;\n timestamp: number;\n messageCount: number;\n totalTokens: number;\n filesModified: string[];\n}\n\nexport interface CheckpointManagerOptions {\n persistPath?: string;\n autoCheckpointInterval?: number; // Messages between auto-checkpoints\n maxCheckpoints?: number; // Max checkpoints to keep per session\n}\n\n/**\n * Real Checkpoint Manager using ONLY SDK features\n * Git-like checkpointing with message UUIDs\n *\n * ✅ VERIFIED: Not fake - actually creates restore points using SDK\n */\nexport class RealCheckpointManager extends EventEmitter {\n private checkpoints = new Map<string, Checkpoint>();\n private sessionMessages = new Map<string, SDKMessage[]>();\n private persistPath: string;\n private autoCheckpointInterval: number;\n private maxCheckpoints: number;\n private messageCounters = new Map<string, number>();\n\n constructor(options: CheckpointManagerOptions = {}) {\n super();\n this.persistPath = options.persistPath || '.claude-flow/checkpoints';\n this.autoCheckpointInterval = options.autoCheckpointInterval || 10; // Every 10 messages\n this.maxCheckpoints = options.maxCheckpoints || 50;\n this.ensurePersistPath();\n }\n\n private async ensurePersistPath() {\n try {\n await fs.mkdir(this.persistPath, { recursive: true });\n } catch (error) {\n // Directory exists\n }\n }\n\n /**\n * Track messages for a session\n * Call this to monitor session progress and enable auto-checkpointing\n */\n async trackSession(\n sessionId: string,\n queryGenerator: Query,\n autoCheckpoint: boolean = false\n ): Promise<void> {\n const messages = this.sessionMessages.get(sessionId) || [];\n this.sessionMessages.set(sessionId, messages);\n\n let messageCount = this.messageCounters.get(sessionId) || 0;\n\n for await (const message of queryGenerator) {\n messages.push(message);\n messageCount++;\n\n this.messageCounters.set(sessionId, messageCount);\n\n this.emit('message:tracked', {\n sessionId,\n messageCount,\n messageType: message.type,\n messageUuid: message.uuid,\n });\n\n // Auto-checkpoint if enabled\n if (autoCheckpoint && messageCount % this.autoCheckpointInterval === 0) {\n await this.createCheckpoint(\n sessionId,\n `Auto-checkpoint at ${messageCount} messages`\n );\n }\n }\n }\n\n /**\n * Create a checkpoint using message UUID\n *\n * ✅ VERIFIED: Checkpoint ID = message UUID (can rollback to this exact point)\n */\n async createCheckpoint(sessionId: string, description: string): Promise<string> {\n const messages = this.sessionMessages.get(sessionId);\n\n if (!messages || messages.length === 0) {\n throw new Error(`No messages tracked for session: ${sessionId}`);\n }\n\n const lastMessage = messages[messages.length - 1];\n const checkpointId = lastMessage.uuid; // ✅ Checkpoint = message UUID!\n\n // Calculate stats\n const totalTokens = this.calculateTotalTokens(messages);\n const filesModified = this.extractFilesModified(messages);\n\n const checkpoint: Checkpoint = {\n id: checkpointId,\n sessionId,\n description,\n timestamp: Date.now(),\n messageCount: messages.length,\n totalTokens,\n filesModified,\n };\n\n this.checkpoints.set(checkpointId, checkpoint);\n await this.persistCheckpoint(checkpoint);\n\n // Enforce max checkpoints limit\n await this.enforceCheckpointLimit(sessionId);\n\n this.emit('checkpoint:created', {\n checkpointId,\n sessionId,\n description,\n messageCount: messages.length,\n });\n\n return checkpointId;\n }\n\n /**\n * Rollback to a checkpoint\n *\n * ✅ VERIFIED: Uses SDK's resumeSessionAt to rewind to exact message UUID\n */\n async rollbackToCheckpoint(\n checkpointId: string,\n continuePrompt?: string\n ): Promise<Query> {\n const checkpoint = this.checkpoints.get(checkpointId);\n\n if (!checkpoint) {\n // Try to load from disk\n const loaded = await this.loadCheckpoint(checkpointId);\n if (!loaded) {\n throw new Error(`Checkpoint not found: ${checkpointId}`);\n }\n }\n\n const chkpt = this.checkpoints.get(checkpointId)!;\n\n // Use SDK's resumeSessionAt to rollback to checkpoint\n const rolledBackQuery = query({\n prompt: continuePrompt || 'Continue from checkpoint',\n options: {\n resume: chkpt.sessionId,\n resumeSessionAt: checkpointId, // ✅ SDK rewinds to this message UUID!\n }\n });\n\n this.emit('checkpoint:rollback', {\n checkpointId,\n sessionId: chkpt.sessionId,\n description: chkpt.description,\n });\n\n return rolledBackQuery;\n }\n\n /**\n * List checkpoints for a session\n */\n listCheckpoints(sessionId: string): Checkpoint[] {\n return Array.from(this.checkpoints.values())\n .filter(c => c.sessionId === sessionId)\n .sort((a, b) => b.timestamp - a.timestamp);\n }\n\n /**\n * Get checkpoint info\n */\n getCheckpoint(checkpointId: string): Checkpoint | undefined {\n return this.checkpoints.get(checkpointId);\n }\n\n /**\n * Delete a checkpoint\n */\n async deleteCheckpoint(checkpointId: string): Promise<void> {\n const checkpoint = this.checkpoints.get(checkpointId);\n\n if (checkpoint) {\n this.checkpoints.delete(checkpointId);\n await this.deletePersistedCheckpoint(checkpointId);\n\n this.emit('checkpoint:deleted', {\n checkpointId,\n sessionId: checkpoint.sessionId,\n });\n }\n }\n\n /**\n * Calculate diff between two checkpoints\n */\n getCheckpointDiff(fromId: string, toId: string): {\n messagesDiff: number;\n tokensDiff: number;\n filesAdded: string[];\n filesRemoved: string[];\n } {\n const from = this.checkpoints.get(fromId);\n const to = this.checkpoints.get(toId);\n\n if (!from || !to) {\n throw new Error('Checkpoint not found');\n }\n\n const fromFiles = new Set(from.filesModified);\n const toFiles = new Set(to.filesModified);\n\n const filesAdded = Array.from(toFiles).filter(f => !fromFiles.has(f));\n const filesRemoved = Array.from(fromFiles).filter(f => !toFiles.has(f));\n\n return {\n messagesDiff: to.messageCount - from.messageCount,\n tokensDiff: to.totalTokens - from.totalTokens,\n filesAdded,\n filesRemoved,\n };\n }\n\n /**\n * Calculate total tokens from messages\n */\n private calculateTotalTokens(messages: SDKMessage[]): number {\n let total = 0;\n\n for (const msg of messages) {\n if ('message' in msg && 'usage' in msg.message) {\n const usage = msg.message.usage as { input_tokens?: number; output_tokens?: number };\n total += (usage.input_tokens || 0) + (usage.output_tokens || 0);\n }\n }\n\n return total;\n }\n\n /**\n * Extract files modified from messages\n */\n private extractFilesModified(messages: SDKMessage[]): string[] {\n const files = new Set<string>();\n\n for (const msg of messages) {\n if (msg.type === 'assistant' && 'message' in msg) {\n const content = msg.message.content;\n for (const block of content) {\n if (block.type === 'tool_use') {\n // Check for file operations\n if (block.name === 'Edit' || block.name === 'Write' || block.name === 'FileEdit' || block.name === 'FileWrite') {\n const input = block.input as { file_path?: string };\n if (input.file_path) {\n files.add(input.file_path);\n }\n }\n }\n }\n }\n }\n\n return Array.from(files);\n }\n\n /**\n * Persist checkpoint to disk\n */\n private async persistCheckpoint(checkpoint: Checkpoint): Promise<void> {\n const filePath = join(this.persistPath, `${checkpoint.id}.json`);\n\n try {\n await fs.writeFile(\n filePath,\n JSON.stringify(checkpoint, null, 2),\n 'utf-8'\n );\n\n this.emit('persist:saved', {\n checkpointId: checkpoint.id,\n filePath,\n });\n } catch (error) {\n this.emit('persist:error', {\n checkpointId: checkpoint.id,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n /**\n * Load checkpoint from disk\n */\n private async loadCheckpoint(checkpointId: string): Promise<boolean> {\n const filePath = join(this.persistPath, `${checkpointId}.json`);\n\n try {\n const data = await fs.readFile(filePath, 'utf-8');\n const checkpoint = JSON.parse(data) as Checkpoint;\n\n this.checkpoints.set(checkpointId, checkpoint);\n this.emit('persist:loaded', { checkpointId, filePath });\n\n return true;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Delete persisted checkpoint\n */\n private async deletePersistedCheckpoint(checkpointId: string): Promise<void> {\n const filePath = join(this.persistPath, `${checkpointId}.json`);\n\n try {\n await fs.unlink(filePath);\n this.emit('persist:deleted', { checkpointId });\n } catch (error) {\n // File doesn't exist, ignore\n }\n }\n\n /**\n * Enforce max checkpoint limit per session\n */\n private async enforceCheckpointLimit(sessionId: string): Promise<void> {\n const sessionCheckpoints = this.listCheckpoints(sessionId);\n\n if (sessionCheckpoints.length > this.maxCheckpoints) {\n // Delete oldest checkpoints beyond limit\n const toDelete = sessionCheckpoints.slice(this.maxCheckpoints);\n\n for (const checkpoint of toDelete) {\n await this.deleteCheckpoint(checkpoint.id);\n }\n\n this.emit('checkpoint:limit_enforced', {\n sessionId,\n deleted: toDelete.length,\n });\n }\n }\n\n /**\n * List all persisted checkpoints (even after restart)\n */\n async listPersistedCheckpoints(): Promise<string[]> {\n try {\n const files = await fs.readdir(this.persistPath);\n return files\n .filter(f => f.endsWith('.json'))\n .map(f => f.replace('.json', ''));\n } catch (error) {\n return [];\n }\n }\n\n /**\n * Load all checkpoints from disk\n */\n async loadAllCheckpoints(): Promise<number> {\n const checkpointIds = await this.listPersistedCheckpoints();\n let loaded = 0;\n\n for (const id of checkpointIds) {\n if (await this.loadCheckpoint(id)) {\n loaded++;\n }\n }\n\n this.emit('checkpoints:loaded', { count: loaded });\n return loaded;\n }\n}\n\n// Export singleton instance\nexport const checkpointManager = new RealCheckpointManager();\n"],"names":["query","EventEmitter","promises","fs","join","RealCheckpointManager","checkpoints","Map","sessionMessages","persistPath","autoCheckpointInterval","maxCheckpoints","messageCounters","options","ensurePersistPath","mkdir","recursive","error","trackSession","sessionId","queryGenerator","autoCheckpoint","messages","get","set","messageCount","message","push","emit","messageType","type","messageUuid","uuid","createCheckpoint","description","length","Error","lastMessage","checkpointId","totalTokens","calculateTotalTokens","filesModified","extractFilesModified","checkpoint","id","timestamp","Date","now","persistCheckpoint","enforceCheckpointLimit","rollbackToCheckpoint","continuePrompt","loaded","loadCheckpoint","chkpt","rolledBackQuery","prompt","resume","resumeSessionAt","listCheckpoints","Array","from","values","filter","c","sort","a","b","getCheckpoint","deleteCheckpoint","delete","deletePersistedCheckpoint","getCheckpointDiff","fromId","toId","to","fromFiles","Set","toFiles","filesAdded","f","has","filesRemoved","messagesDiff","tokensDiff","total","msg","usage","input_tokens","output_tokens","files","content","block","name","input","file_path","add","filePath","writeFile","JSON","stringify","String","data","readFile","parse","unlink","sessionCheckpoints","toDelete","slice","deleted","listPersistedCheckpoints","readdir","endsWith","map","replace","loadAllCheckpoints","checkpointIds","count","checkpointManager"],"mappings":"AAYA,SAASA,KAAK,QAAmD,4BAA4B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mBAAmBvE,MAAM,GAAG,IAAI,CAACxB,cAAc,EAAE;YAEnD,MAAMgG,WAAWD,mBAAmBE,KAAK,CAAC,IAAI,CAACjG,cAAc;YAE7D,KAAK,MAAMgC,cAAcgE,SAAU;gBACjC,MAAM,IAAI,CAACtC,gBAAgB,CAAC1B,WAAWC,EAAE;YAC3C;YAEA,IAAI,CAAChB,IAAI,CAAC,6BAA6B;gBACrCT;gBACA0F,SAASF,SAASxE,MAAM;YAC1B;QACF;IACF;IAKA,MAAM2E,2BAA8C;QAClD,IAAI;YACF,MAAMpB,QAAQ,MAAMvF,GAAG4G,OAAO,CAAC,IAAI,CAACtG,WAAW;YAC/C,OAAOiF,MACJ3B,MAAM,CAACiB,CAAAA,IAAKA,EAAEgC,QAAQ,CAAC,UACvBC,GAAG,CAACjC,CAAAA,IAAKA,EAAEkC,OAAO,CAAC,SAAS;QACjC,EAAE,OAAOjG,OAAO;YACd,OAAO,EAAE;QACX;IACF;IAKA,MAAMkG,qBAAsC;QAC1C,MAAMC,gBAAgB,MAAM,IAAI,CAACN,wBAAwB;QACzD,IAAI1D,SAAS;QAEb,KAAK,MAAMR,MAAMwE,cAAe;YAC9B,IAAI,MAAM,IAAI,CAAC/D,cAAc,CAACT,KAAK;gBACjCQ;YACF;QACF;QAEA,IAAI,CAACxB,IAAI,CAAC,sBAAsB;YAAEyF,OAAOjE;QAAO;QAChD,OAAOA;IACT;AACF;AAGA,OAAO,MAAMkE,oBAAoB,IAAIjH,wBAAwB"}
|
|
@@ -385,7 +385,7 @@ async function getStepOptimizations(workflowId, step, context) {
|
|
|
385
385
|
return await context.memory.cache.get(optKey) || [];
|
|
386
386
|
}
|
|
387
387
|
function applyStepOptimizations(state, optimizations) {
|
|
388
|
-
|
|
388
|
+
const optimizedState = {
|
|
389
389
|
...state
|
|
390
390
|
};
|
|
391
391
|
for (const opt of optimizations){
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/services/agentic-flow-hooks/workflow-hooks.ts"],"sourcesContent":["/**\n * Self-improving workflow hooks for agentic-flow\n * \n * Enables adaptive workflows with provider selection\n * and continuous improvement based on outcomes.\n */\n\nimport { agenticHookManager } from './hook-manager.js';\nimport type {\n AgenticHookContext,\n HookHandlerResult,\n WorkflowHookPayload,\n WorkflowDecision,\n Learning,\n SideEffect,\n Pattern,\n} from './types.js';\n\n// ===== Workflow Start Hook =====\n\nexport const workflowStartHook = {\n id: 'agentic-workflow-start',\n type: 'workflow-start' as const,\n priority: 100,\n handler: async (\n payload: WorkflowHookPayload,\n context: AgenticHookContext\n ): Promise<HookHandlerResult> => {\n const { workflowId, state } = payload;\n \n const sideEffects: SideEffect[] = [];\n \n // Load workflow history and learnings\n const history = await loadWorkflowHistory(workflowId, context);\n const learnings = await loadWorkflowLearnings(workflowId, context);\n \n // Select optimal provider based on history\n const provider = await selectOptimalProvider(\n workflowId,\n state,\n history,\n context\n );\n \n // Initialize workflow state\n const enhancedState = {\n ...state,\n startTime: Date.now(),\n provider,\n learnings: learnings.slice(-10), // Last 10 learnings\n predictions: await generateWorkflowPredictions(workflowId, state, context),\n };\n \n // Store workflow session\n sideEffects.push({\n type: 'memory',\n action: 'store',\n data: {\n key: `workflow:session:${workflowId}:${context.sessionId}`,\n value: enhancedState,\n ttl: 86400, // 24 hours\n },\n });\n \n // Track workflow start\n sideEffects.push({\n type: 'metric',\n action: 'increment',\n data: { name: `workflow.starts.${workflowId}` },\n });\n \n return {\n continue: true,\n modified: true,\n payload: {\n ...payload,\n state: enhancedState,\n },\n sideEffects,\n };\n },\n};\n\n// ===== Workflow Step Hook =====\n\nexport const workflowStepHook = {\n id: 'agentic-workflow-step',\n type: 'workflow-step' as const,\n priority: 100,\n handler: async (\n payload: WorkflowHookPayload,\n context: AgenticHookContext\n ): Promise<HookHandlerResult> => {\n const { workflowId, step, state } = payload;\n \n if (!step) {\n return { continue: true };\n }\n \n const sideEffects: SideEffect[] = [];\n \n // Measure step performance\n const stepStart = Date.now();\n \n // Check for step optimizations\n const optimizations = await getStepOptimizations(\n workflowId,\n step,\n context\n );\n \n if (optimizations.length > 0) {\n // Apply step optimizations\n const optimizedState = applyStepOptimizations(\n state,\n optimizations\n );\n \n sideEffects.push({\n type: 'log',\n action: 'write',\n data: {\n level: 'info',\n message: `Applied ${optimizations.length} optimizations to step ${step}`,\n data: { optimizations },\n },\n });\n \n return {\n continue: true,\n modified: true,\n payload: {\n ...payload,\n state: optimizedState,\n },\n sideEffects,\n };\n }\n \n // Track step execution\n sideEffects.push({\n type: 'memory',\n action: 'store',\n data: {\n key: `workflow:step:${workflowId}:${step}:${Date.now()}`,\n value: {\n step,\n state: summarizeState(state),\n timestamp: Date.now(),\n },\n ttl: 86400,\n },\n });\n \n return {\n continue: true,\n sideEffects,\n };\n },\n};\n\n// ===== Workflow Decision Hook =====\n\nexport const workflowDecisionHook = {\n id: 'agentic-workflow-decision',\n type: 'workflow-decision' as const,\n priority: 90,\n handler: async (\n payload: WorkflowHookPayload,\n context: AgenticHookContext\n ): Promise<HookHandlerResult> => {\n const { workflowId, decision, state } = payload;\n \n if (!decision) {\n return { continue: true };\n }\n \n const sideEffects: SideEffect[] = [];\n \n // Enhance decision with historical data\n const historicalOutcomes = await getDecisionOutcomes(\n workflowId,\n decision.point,\n context\n );\n \n // Calculate confidence adjustments\n const adjustedDecision = adjustDecisionConfidence(\n decision,\n historicalOutcomes\n );\n \n // Generate alternative paths\n const alternatives = await generateAlternativeDecisions(\n workflowId,\n decision,\n state,\n context\n );\n \n if (alternatives.length > 0) {\n // Check if better alternative exists\n const bestAlternative = alternatives.find(alt => \n alt.confidence > adjustedDecision.confidence * 1.2\n );\n \n if (bestAlternative) {\n sideEffects.push({\n type: 'notification',\n action: 'emit',\n data: {\n event: 'workflow:decision:alternative',\n data: {\n original: adjustedDecision,\n suggested: bestAlternative,\n },\n },\n });\n \n // Override with better decision\n adjustedDecision.selected = bestAlternative.selected;\n adjustedDecision.confidence = bestAlternative.confidence;\n adjustedDecision.reasoning = `${adjustedDecision.reasoning} (AI-optimized)`;\n }\n }\n \n // Store decision for learning\n sideEffects.push({\n type: 'memory',\n action: 'store',\n data: {\n key: `decision:${workflowId}:${decision.point}:${Date.now()}`,\n value: {\n ...adjustedDecision,\n alternatives,\n state: summarizeState(state),\n },\n ttl: 604800, // 7 days\n },\n });\n \n // Track decision metrics\n sideEffects.push({\n type: 'metric',\n action: 'update',\n data: {\n name: `workflow.decisions.confidence.${workflowId}`,\n value: adjustedDecision.confidence,\n },\n });\n \n return {\n continue: true,\n modified: true,\n payload: {\n ...payload,\n decision: adjustedDecision,\n },\n sideEffects,\n };\n },\n};\n\n// ===== Workflow Complete Hook =====\n\nexport const workflowCompleteHook = {\n id: 'agentic-workflow-complete',\n type: 'workflow-complete' as const,\n priority: 100,\n handler: async (\n payload: WorkflowHookPayload,\n context: AgenticHookContext\n ): Promise<HookHandlerResult> => {\n const { workflowId, state, metrics } = payload;\n \n const sideEffects: SideEffect[] = [];\n \n // Calculate workflow performance\n const performance = calculateWorkflowPerformance(state, metrics);\n \n // Extract learnings from this execution\n const learnings = await extractWorkflowLearnings(\n workflowId,\n state,\n performance,\n context\n );\n \n // Store learnings\n for (const learning of learnings) {\n sideEffects.push({\n type: 'memory',\n action: 'store',\n data: {\n key: `learning:${workflowId}:${learning.type}:${Date.now()}`,\n value: learning,\n ttl: 0, // Permanent\n },\n });\n }\n \n // Update workflow success patterns\n if (performance.success) {\n const pattern: Pattern = {\n id: `workflow_success_${Date.now()}`,\n type: 'success',\n confidence: performance.score,\n occurrences: 1,\n context: {\n workflowId,\n provider: state.provider,\n duration: metrics?.duration || 0,\n decisions: countDecisions(state),\n },\n };\n \n context.neural.patterns.add(pattern);\n \n sideEffects.push({\n type: 'neural',\n action: 'train',\n data: {\n patterns: [pattern],\n modelId: `workflow-optimizer-${workflowId}`,\n },\n });\n }\n \n // Generate improvement suggestions\n const improvements = await generateImprovementSuggestions(\n workflowId,\n state,\n performance,\n learnings,\n context\n );\n \n if (improvements.length > 0) {\n sideEffects.push({\n type: 'notification',\n action: 'emit',\n data: {\n event: 'workflow:improvements:suggested',\n data: {\n workflowId,\n improvements,\n performance,\n },\n },\n });\n }\n \n // Update workflow metrics\n sideEffects.push(\n {\n type: 'metric',\n action: 'update',\n data: {\n name: `workflow.completion.rate.${workflowId}`,\n value: performance.success ? 1 : 0,\n },\n },\n {\n type: 'metric',\n action: 'update',\n data: {\n name: `workflow.performance.score.${workflowId}`,\n value: performance.score,\n },\n }\n );\n \n return {\n continue: true,\n sideEffects,\n };\n },\n};\n\n// ===== Workflow Error Hook =====\n\nexport const workflowErrorHook = {\n id: 'agentic-workflow-error',\n type: 'workflow-error' as const,\n priority: 95,\n handler: async (\n payload: WorkflowHookPayload,\n context: AgenticHookContext\n ): Promise<HookHandlerResult> => {\n const { workflowId, error, state } = payload;\n \n if (!error) {\n return { continue: true };\n }\n \n const sideEffects: SideEffect[] = [];\n \n // Analyze error pattern\n const errorPattern = await analyzeErrorPattern(\n workflowId,\n error,\n state,\n context\n );\n \n // Store error for learning\n sideEffects.push({\n type: 'memory',\n action: 'store',\n data: {\n key: `error:${workflowId}:${Date.now()}`,\n value: {\n error: {\n message: error.message,\n stack: error.stack,\n type: error.name,\n },\n pattern: errorPattern,\n state: summarizeState(state),\n timestamp: Date.now(),\n },\n ttl: 604800, // 7 days\n },\n });\n \n // Check for recovery strategies\n const recovery = await findRecoveryStrategy(\n workflowId,\n error,\n errorPattern,\n context\n );\n \n if (recovery) {\n sideEffects.push({\n type: 'log',\n action: 'write',\n data: {\n level: 'info',\n message: 'Recovery strategy found',\n data: recovery,\n },\n });\n \n // Apply recovery\n const recoveredState = applyRecoveryStrategy(state, recovery);\n \n return {\n continue: true,\n modified: true,\n payload: {\n ...payload,\n state: recoveredState,\n error: undefined, // Clear error after recovery\n },\n sideEffects,\n };\n }\n \n // Learn from failure\n const failureLearning: Learning = {\n type: 'failure',\n context: `Error in workflow ${workflowId}: ${error.message}`,\n value: {\n errorType: error.name,\n state: summarizeState(state),\n pattern: errorPattern,\n },\n applicability: errorPattern.confidence,\n };\n \n sideEffects.push({\n type: 'memory',\n action: 'store',\n data: {\n key: `learning:failure:${workflowId}:${Date.now()}`,\n value: failureLearning,\n ttl: 0, // Permanent\n },\n });\n \n return {\n continue: true,\n sideEffects,\n };\n },\n};\n\n// ===== Helper Functions =====\n\nasync function loadWorkflowHistory(\n workflowId: string,\n context: AgenticHookContext\n): Promise<any[]> {\n const historyKey = `workflow:history:${workflowId}`;\n return await context.memory.cache.get(historyKey) || [];\n}\n\nasync function loadWorkflowLearnings(\n workflowId: string,\n context: AgenticHookContext\n): Promise<Learning[]> {\n const learningsKey = `workflow:learnings:${workflowId}`;\n return await context.memory.cache.get(learningsKey) || [];\n}\n\nasync function selectOptimalProvider(\n workflowId: string,\n state: any,\n history: any[],\n context: AgenticHookContext\n): Promise<string> {\n // Analyze historical performance by provider\n const providerStats = new Map<string, { success: number; total: number }>();\n \n for (const execution of history) {\n const provider = execution.provider;\n if (!provider) continue;\n \n const stats = providerStats.get(provider) || { success: 0, total: 0 };\n stats.total++;\n if (execution.success) stats.success++;\n providerStats.set(provider, stats);\n }\n \n // Calculate success rates\n let bestProvider = 'openai'; // Default\n let bestRate = 0;\n \n for (const [provider, stats] of providerStats) {\n const rate = stats.success / stats.total;\n if (rate > bestRate && stats.total >= 5) {\n bestRate = rate;\n bestProvider = provider;\n }\n }\n \n // Check current provider health\n const healthKey = `provider:health:${bestProvider}`;\n const health = await context.memory.cache.get(healthKey);\n \n if (health && health.score < 0.5) {\n // Provider unhealthy, select alternative\n return selectAlternativeProvider(bestProvider, providerStats);\n }\n \n return bestProvider;\n}\n\nasync function generateWorkflowPredictions(\n workflowId: string,\n state: any,\n context: AgenticHookContext\n): Promise<any> {\n // Generate predictions for workflow execution\n const predictions = {\n estimatedDuration: 0,\n successProbability: 0.7,\n likelyBottlenecks: [],\n recommendedOptimizations: [],\n };\n \n // Load historical durations\n const history = await loadWorkflowHistory(workflowId, context);\n if (history.length > 0) {\n const durations = history\n .filter(h => h.duration)\n .map(h => h.duration);\n \n if (durations.length > 0) {\n predictions.estimatedDuration = \n durations.reduce((a, b) => a + b, 0) / durations.length;\n }\n \n const successes = history.filter(h => h.success).length;\n predictions.successProbability = successes / history.length;\n }\n \n return predictions;\n}\n\nasync function getStepOptimizations(\n workflowId: string,\n step: string,\n context: AgenticHookContext\n): Promise<any[]> {\n // Get optimizations for specific step\n const optKey = `optimizations:${workflowId}:${step}`;\n return await context.memory.cache.get(optKey) || [];\n}\n\nfunction applyStepOptimizations(\n state: any,\n optimizations: any[]\n): any {\n let optimizedState = { ...state };\n \n for (const opt of optimizations) {\n switch (opt.type) {\n case 'skip':\n if (opt.condition && opt.condition(state)) {\n optimizedState.skipSteps = [\n ...(optimizedState.skipSteps || []),\n opt.target,\n ];\n }\n break;\n \n case 'parallel':\n optimizedState.parallelSteps = [\n ...(optimizedState.parallelSteps || []),\n ...opt.steps,\n ];\n break;\n \n case 'cache':\n optimizedState.useCache = true;\n optimizedState.cacheKeys = [\n ...(optimizedState.cacheKeys || []),\n opt.key,\n ];\n break;\n }\n }\n \n return optimizedState;\n}\n\nfunction summarizeState(state: any): any {\n // Create summary of state for storage\n return {\n keys: Object.keys(state),\n size: JSON.stringify(state).length,\n hasError: !!state.error,\n provider: state.provider,\n timestamp: Date.now(),\n };\n}\n\nasync function getDecisionOutcomes(\n workflowId: string,\n decisionPoint: string,\n context: AgenticHookContext\n): Promise<any[]> {\n // Get historical outcomes for decision point\n const outcomeKey = `outcomes:${workflowId}:${decisionPoint}`;\n return await context.memory.cache.get(outcomeKey) || [];\n}\n\nfunction adjustDecisionConfidence(\n decision: WorkflowDecision,\n historicalOutcomes: any[]\n): WorkflowDecision {\n if (historicalOutcomes.length === 0) {\n return decision;\n }\n \n // Calculate success rate for selected option\n const relevantOutcomes = historicalOutcomes.filter(o => \n o.selected === decision.selected\n );\n \n if (relevantOutcomes.length === 0) {\n return decision;\n }\n \n const successRate = relevantOutcomes.filter(o => o.success).length / \n relevantOutcomes.length;\n \n // Adjust confidence based on historical success\n const adjustedConfidence = decision.confidence * 0.7 + successRate * 0.3;\n \n return {\n ...decision,\n confidence: adjustedConfidence,\n learnings: [\n ...decision.learnings,\n {\n type: 'success',\n context: `Historical success rate: ${(successRate * 100).toFixed(1)}%`,\n value: successRate,\n applicability: Math.min(relevantOutcomes.length / 10, 1),\n },\n ],\n };\n}\n\nasync function generateAlternativeDecisions(\n workflowId: string,\n decision: WorkflowDecision,\n state: any,\n context: AgenticHookContext\n): Promise<WorkflowDecision[]> {\n // Generate alternative decision paths\n const alternatives: WorkflowDecision[] = [];\n \n // Check each option not selected\n for (const option of decision.options) {\n if (option === decision.selected) continue;\n \n // Calculate alternative confidence\n const altConfidence = await calculateAlternativeConfidence(\n workflowId,\n decision.point,\n option,\n state,\n context\n );\n \n if (altConfidence > 0.5) {\n alternatives.push({\n ...decision,\n selected: option,\n confidence: altConfidence,\n reasoning: `Alternative path based on historical analysis`,\n });\n }\n }\n \n return alternatives;\n}\n\nfunction calculateWorkflowPerformance(\n state: any,\n metrics: any\n): any {\n const performance = {\n success: !state.error,\n score: 0,\n duration: metrics?.duration || 0,\n efficiency: 0,\n reliability: 0,\n };\n \n // Calculate performance score\n if (performance.success) {\n performance.score = 0.7; // Base success score\n \n // Adjust for duration\n if (metrics?.duration && state.predictions?.estimatedDuration) {\n const durationRatio = state.predictions.estimatedDuration / metrics.duration;\n performance.efficiency = Math.min(durationRatio, 1);\n performance.score += performance.efficiency * 0.2;\n }\n \n // Adjust for error rate\n if (metrics?.errorRate !== undefined) {\n performance.reliability = 1 - metrics.errorRate;\n performance.score += performance.reliability * 0.1;\n }\n }\n \n return performance;\n}\n\nasync function extractWorkflowLearnings(\n workflowId: string,\n state: any,\n performance: any,\n context: AgenticHookContext\n): Promise<Learning[]> {\n const learnings: Learning[] = [];\n \n // Learn from successful execution\n if (performance.success) {\n learnings.push({\n type: 'success',\n context: `Successful workflow execution with score ${performance.score}`,\n value: {\n provider: state.provider,\n duration: performance.duration,\n decisions: extractDecisions(state),\n },\n applicability: performance.score,\n });\n }\n \n // Learn from optimizations\n if (state.appliedOptimizations) {\n for (const opt of state.appliedOptimizations) {\n learnings.push({\n type: 'optimization',\n context: `Applied ${opt.type} optimization at ${opt.step}`,\n value: opt,\n applicability: 0.8,\n });\n }\n }\n \n return learnings;\n}\n\nfunction countDecisions(state: any): number {\n // Count decisions made during workflow\n return state.decisions?.length || 0;\n}\n\nasync function generateImprovementSuggestions(\n workflowId: string,\n state: any,\n performance: any,\n learnings: Learning[],\n context: AgenticHookContext\n): Promise<any[]> {\n const suggestions: any[] = [];\n \n // Suggest caching if repeated operations\n if (performance.duration > 5000) {\n suggestions.push({\n type: 'cache',\n target: 'frequent_operations',\n reason: 'Long execution time detected',\n expectedImprovement: '30-50% reduction in duration',\n });\n }\n \n // Suggest parallelization\n if (state.sequentialSteps?.length > 3) {\n suggestions.push({\n type: 'parallel',\n target: 'independent_steps',\n reason: 'Multiple sequential steps detected',\n expectedImprovement: '40-60% reduction in duration',\n });\n }\n \n // Suggest provider switch based on learnings\n const providerLearnings = learnings.filter(l => \n l.type === 'success' && l.value.provider\n );\n \n if (providerLearnings.length > 0) {\n const providerScores = new Map<string, number>();\n for (const learning of providerLearnings) {\n const provider = learning.value.provider;\n const score = providerScores.get(provider) || 0;\n providerScores.set(provider, score + learning.applicability);\n }\n \n const currentScore = providerScores.get(state.provider) || 0;\n for (const [provider, score] of providerScores) {\n if (score > currentScore * 1.2) {\n suggestions.push({\n type: 'provider',\n target: provider,\n reason: `${provider} shows better historical performance`,\n expectedImprovement: `${((score / currentScore - 1) * 100).toFixed(0)}% better reliability`,\n });\n }\n }\n }\n \n return suggestions;\n}\n\nasync function analyzeErrorPattern(\n workflowId: string,\n error: Error,\n state: any,\n context: AgenticHookContext\n): Promise<any> {\n // Analyze error to find patterns\n const pattern = {\n type: classifyError(error),\n confidence: 0.7,\n context: {\n step: state.currentStep,\n provider: state.provider,\n errorMessage: error.message,\n },\n };\n \n // Check for similar errors\n const errorHistory = await context.memory.cache.get(\n `errors:${workflowId}:${pattern.type}`\n ) || [];\n \n if (errorHistory.length > 5) {\n pattern.confidence = 0.9;\n pattern.context.recurring = true;\n pattern.context.occurrences = errorHistory.length;\n }\n \n return pattern;\n}\n\nasync function findRecoveryStrategy(\n workflowId: string,\n error: Error,\n errorPattern: any,\n context: AgenticHookContext\n): Promise<any | null> {\n // Find recovery strategy for error\n if (errorPattern.type === 'timeout') {\n return {\n type: 'retry',\n params: {\n maxRetries: 3,\n backoff: 'exponential',\n timeout: 30000,\n },\n };\n }\n \n if (errorPattern.type === 'rate_limit') {\n return {\n type: 'throttle',\n params: {\n delay: 1000,\n maxConcurrent: 1,\n },\n };\n }\n \n if (errorPattern.type === 'validation') {\n return {\n type: 'transform',\n params: {\n sanitize: true,\n validate: true,\n },\n };\n }\n \n return null;\n}\n\nfunction applyRecoveryStrategy(state: any, recovery: any): any {\n const recoveredState = { ...state };\n \n switch (recovery.type) {\n case 'retry':\n recoveredState.retryConfig = recovery.params;\n recoveredState.shouldRetry = true;\n break;\n \n case 'throttle':\n recoveredState.throttleConfig = recovery.params;\n recoveredState.throttled = true;\n break;\n \n case 'transform':\n recoveredState.transformConfig = recovery.params;\n recoveredState.needsTransform = true;\n break;\n }\n \n recoveredState.recoveryApplied = recovery;\n delete recoveredState.error; // Clear error state\n \n return recoveredState;\n}\n\nfunction selectAlternativeProvider(\n currentProvider: string,\n providerStats: Map<string, { success: number; total: number }>\n): string {\n // Select alternative provider based on stats\n let bestAlternative = 'anthropic'; // Default fallback\n let bestRate = 0;\n \n for (const [provider, stats] of providerStats) {\n if (provider === currentProvider) continue;\n \n const rate = stats.success / stats.total;\n if (rate > bestRate && stats.total >= 3) {\n bestRate = rate;\n bestAlternative = provider;\n }\n }\n \n return bestAlternative;\n}\n\nasync function calculateAlternativeConfidence(\n workflowId: string,\n decisionPoint: string,\n option: string,\n state: any,\n context: AgenticHookContext\n): Promise<number> {\n // Calculate confidence for alternative option\n const outcomeKey = `outcomes:${workflowId}:${decisionPoint}:${option}`;\n const outcomes = await context.memory.cache.get(outcomeKey) || [];\n \n if (outcomes.length === 0) {\n return 0.5; // Default confidence\n }\n \n const successRate = outcomes.filter((o: any) => o.success).length / \n outcomes.length;\n \n // Adjust for recency\n const recentOutcomes = outcomes.slice(-10);\n const recentSuccessRate = recentOutcomes.filter((o: any) => o.success).length / \n recentOutcomes.length;\n \n return successRate * 0.7 + recentSuccessRate * 0.3;\n}\n\nfunction extractDecisions(state: any): any[] {\n // Extract decisions from state\n return state.decisions || [];\n}\n\nfunction classifyError(error: Error): string {\n const message = error.message.toLowerCase();\n \n if (message.includes('timeout')) return 'timeout';\n if (message.includes('rate limit')) return 'rate_limit';\n if (message.includes('validation')) return 'validation';\n if (message.includes('network')) return 'network';\n if (message.includes('auth')) return 'authentication';\n \n return 'unknown';\n}\n\n// ===== Register Hooks =====\n\nexport function registerWorkflowHooks(): void {\n agenticHookManager.register(workflowStartHook);\n agenticHookManager.register(workflowStepHook);\n agenticHookManager.register(workflowDecisionHook);\n agenticHookManager.register(workflowCompleteHook);\n agenticHookManager.register(workflowErrorHook);\n}"],"names":["agenticHookManager","workflowStartHook","id","type","priority","handler","payload","context","workflowId","state","sideEffects","history","loadWorkflowHistory","learnings","loadWorkflowLearnings","provider","selectOptimalProvider","enhancedState","startTime","Date","now","slice","predictions","generateWorkflowPredictions","push","action","data","key","sessionId","value","ttl","name","continue","modified","workflowStepHook","step","stepStart","optimizations","getStepOptimizations","length","optimizedState","applyStepOptimizations","level","message","summarizeState","timestamp","workflowDecisionHook","decision","historicalOutcomes","getDecisionOutcomes","point","adjustedDecision","adjustDecisionConfidence","alternatives","generateAlternativeDecisions","bestAlternative","find","alt","confidence","event","original","suggested","selected","reasoning","workflowCompleteHook","metrics","performance","calculateWorkflowPerformance","extractWorkflowLearnings","learning","success","pattern","score","occurrences","duration","decisions","countDecisions","neural","patterns","add","modelId","improvements","generateImprovementSuggestions","workflowErrorHook","error","errorPattern","analyzeErrorPattern","stack","recovery","findRecoveryStrategy","recoveredState","applyRecoveryStrategy","undefined","failureLearning","errorType","applicability","historyKey","memory","cache","get","learningsKey","providerStats","Map","execution","stats","total","set","bestProvider","bestRate","rate","healthKey","health","selectAlternativeProvider","estimatedDuration","successProbability","likelyBottlenecks","recommendedOptimizations","durations","filter","h","map","reduce","a","b","successes","optKey","opt","condition","skipSteps","target","parallelSteps","steps","useCache","cacheKeys","keys","Object","size","JSON","stringify","hasError","decisionPoint","outcomeKey","relevantOutcomes","o","successRate","adjustedConfidence","toFixed","Math","min","option","options","altConfidence","calculateAlternativeConfidence","efficiency","reliability","durationRatio","errorRate","extractDecisions","appliedOptimizations","suggestions","reason","expectedImprovement","sequentialSteps","providerLearnings","l","providerScores","currentScore","classifyError","currentStep","errorMessage","errorHistory","recurring","params","maxRetries","backoff","timeout","delay","maxConcurrent","sanitize","validate","retryConfig","shouldRetry","throttleConfig","throttled","transformConfig","needsTransform","recoveryApplied","currentProvider","outcomes","recentOutcomes","recentSuccessRate","toLowerCase","includes","registerWorkflowHooks","register"],"mappings":"AAOA,SAASA,kBAAkB,QAAQ,oBAAoB;AAavD,OAAO,MAAMC,oBAAoB;IAC/BC,IAAI;IACJC,MAAM;IACNC,UAAU;IACVC,SAAS,OACPC,SACAC;QAEA,MAAM,EAAEC,UAAU,EAAEC,KAAK,EAAE,GAAGH;QAE9B,MAAMI,cAA4B,EAAE;QAGpC,MAAMC,UAAU,MAAMC,oBAAoBJ,YAAYD;QACtD,MAAMM,YAAY,MAAMC,sBAAsBN,YAAYD;QAG1D,MAAMQ,WAAW,MAAMC,sBACrBR,YACAC,OACAE,SACAJ;QAIF,MAAMU,gBAAgB;YACpB,GAAGR,KAAK;YACRS,WAAWC,KAAKC,GAAG;YACnBL;YACAF,WAAWA,UAAUQ,KAAK,CAAC,CAAC;YAC5BC,aAAa,MAAMC,4BAA4Bf,YAAYC,OAAOF;QACpE;QAGAG,YAAYc,IAAI,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OAAO;IACxC,IAAIrJ,QAAQqJ,QAAQ,CAAC,SAAS,OAAO;IAErC,OAAO;AACT;AAIA,OAAO,SAASC;IACdjM,mBAAmBkM,QAAQ,CAACjM;IAC5BD,mBAAmBkM,QAAQ,CAAChK;IAC5BlC,mBAAmBkM,QAAQ,CAACpJ;IAC5B9C,mBAAmBkM,QAAQ,CAAClI;IAC5BhE,mBAAmBkM,QAAQ,CAAC/G;AAC9B"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/services/agentic-flow-hooks/workflow-hooks.ts"],"sourcesContent":["/**\n * Self-improving workflow hooks for agentic-flow\n * \n * Enables adaptive workflows with provider selection\n * and continuous improvement based on outcomes.\n */\n\nimport { agenticHookManager } from './hook-manager.js';\nimport type {\n AgenticHookContext,\n HookHandlerResult,\n WorkflowHookPayload,\n WorkflowDecision,\n Learning,\n SideEffect,\n Pattern,\n} from './types.js';\n\n// ===== Workflow Start Hook =====\n\nexport const workflowStartHook = {\n id: 'agentic-workflow-start',\n type: 'workflow-start' as const,\n priority: 100,\n handler: async (\n payload: WorkflowHookPayload,\n context: AgenticHookContext\n ): Promise<HookHandlerResult> => {\n const { workflowId, state } = payload;\n \n const sideEffects: SideEffect[] = [];\n \n // Load workflow history and learnings\n const history = await loadWorkflowHistory(workflowId, context);\n const learnings = await loadWorkflowLearnings(workflowId, context);\n \n // Select optimal provider based on history\n const provider = await selectOptimalProvider(\n workflowId,\n state,\n history,\n context\n );\n \n // Initialize workflow state\n const enhancedState = {\n ...state,\n startTime: Date.now(),\n provider,\n learnings: learnings.slice(-10), // Last 10 learnings\n predictions: await generateWorkflowPredictions(workflowId, state, context),\n };\n \n // Store workflow session\n sideEffects.push({\n type: 'memory',\n action: 'store',\n data: {\n key: `workflow:session:${workflowId}:${context.sessionId}`,\n value: enhancedState,\n ttl: 86400, // 24 hours\n },\n });\n \n // Track workflow start\n sideEffects.push({\n type: 'metric',\n action: 'increment',\n data: { name: `workflow.starts.${workflowId}` },\n });\n \n return {\n continue: true,\n modified: true,\n payload: {\n ...payload,\n state: enhancedState,\n },\n sideEffects,\n };\n },\n};\n\n// ===== Workflow Step Hook =====\n\nexport const workflowStepHook = {\n id: 'agentic-workflow-step',\n type: 'workflow-step' as const,\n priority: 100,\n handler: async (\n payload: WorkflowHookPayload,\n context: AgenticHookContext\n ): Promise<HookHandlerResult> => {\n const { workflowId, step, state } = payload;\n \n if (!step) {\n return { continue: true };\n }\n \n const sideEffects: SideEffect[] = [];\n \n // Measure step performance\n const stepStart = Date.now();\n \n // Check for step optimizations\n const optimizations = await getStepOptimizations(\n workflowId,\n step,\n context\n );\n \n if (optimizations.length > 0) {\n // Apply step optimizations\n const optimizedState = applyStepOptimizations(\n state,\n optimizations\n );\n \n sideEffects.push({\n type: 'log',\n action: 'write',\n data: {\n level: 'info',\n message: `Applied ${optimizations.length} optimizations to step ${step}`,\n data: { optimizations },\n },\n });\n \n return {\n continue: true,\n modified: true,\n payload: {\n ...payload,\n state: optimizedState,\n },\n sideEffects,\n };\n }\n \n // Track step execution\n sideEffects.push({\n type: 'memory',\n action: 'store',\n data: {\n key: `workflow:step:${workflowId}:${step}:${Date.now()}`,\n value: {\n step,\n state: summarizeState(state),\n timestamp: Date.now(),\n },\n ttl: 86400,\n },\n });\n \n return {\n continue: true,\n sideEffects,\n };\n },\n};\n\n// ===== Workflow Decision Hook =====\n\nexport const workflowDecisionHook = {\n id: 'agentic-workflow-decision',\n type: 'workflow-decision' as const,\n priority: 90,\n handler: async (\n payload: WorkflowHookPayload,\n context: AgenticHookContext\n ): Promise<HookHandlerResult> => {\n const { workflowId, decision, state } = payload;\n \n if (!decision) {\n return { continue: true };\n }\n \n const sideEffects: SideEffect[] = [];\n \n // Enhance decision with historical data\n const historicalOutcomes = await getDecisionOutcomes(\n workflowId,\n decision.point,\n context\n );\n \n // Calculate confidence adjustments\n const adjustedDecision = adjustDecisionConfidence(\n decision,\n historicalOutcomes\n );\n \n // Generate alternative paths\n const alternatives = await generateAlternativeDecisions(\n workflowId,\n decision,\n state,\n context\n );\n \n if (alternatives.length > 0) {\n // Check if better alternative exists\n const bestAlternative = alternatives.find(alt => \n alt.confidence > adjustedDecision.confidence * 1.2\n );\n \n if (bestAlternative) {\n sideEffects.push({\n type: 'notification',\n action: 'emit',\n data: {\n event: 'workflow:decision:alternative',\n data: {\n original: adjustedDecision,\n suggested: bestAlternative,\n },\n },\n });\n \n // Override with better decision\n adjustedDecision.selected = bestAlternative.selected;\n adjustedDecision.confidence = bestAlternative.confidence;\n adjustedDecision.reasoning = `${adjustedDecision.reasoning} (AI-optimized)`;\n }\n }\n \n // Store decision for learning\n sideEffects.push({\n type: 'memory',\n action: 'store',\n data: {\n key: `decision:${workflowId}:${decision.point}:${Date.now()}`,\n value: {\n ...adjustedDecision,\n alternatives,\n state: summarizeState(state),\n },\n ttl: 604800, // 7 days\n },\n });\n \n // Track decision metrics\n sideEffects.push({\n type: 'metric',\n action: 'update',\n data: {\n name: `workflow.decisions.confidence.${workflowId}`,\n value: adjustedDecision.confidence,\n },\n });\n \n return {\n continue: true,\n modified: true,\n payload: {\n ...payload,\n decision: adjustedDecision,\n },\n sideEffects,\n };\n },\n};\n\n// ===== Workflow Complete Hook =====\n\nexport const workflowCompleteHook = {\n id: 'agentic-workflow-complete',\n type: 'workflow-complete' as const,\n priority: 100,\n handler: async (\n payload: WorkflowHookPayload,\n context: AgenticHookContext\n ): Promise<HookHandlerResult> => {\n const { workflowId, state, metrics } = payload;\n \n const sideEffects: SideEffect[] = [];\n \n // Calculate workflow performance\n const performance = calculateWorkflowPerformance(state, metrics);\n \n // Extract learnings from this execution\n const learnings = await extractWorkflowLearnings(\n workflowId,\n state,\n performance,\n context\n );\n \n // Store learnings\n for (const learning of learnings) {\n sideEffects.push({\n type: 'memory',\n action: 'store',\n data: {\n key: `learning:${workflowId}:${learning.type}:${Date.now()}`,\n value: learning,\n ttl: 0, // Permanent\n },\n });\n }\n \n // Update workflow success patterns\n if (performance.success) {\n const pattern: Pattern = {\n id: `workflow_success_${Date.now()}`,\n type: 'success',\n confidence: performance.score,\n occurrences: 1,\n context: {\n workflowId,\n provider: state.provider,\n duration: metrics?.duration || 0,\n decisions: countDecisions(state),\n },\n };\n \n context.neural.patterns.add(pattern);\n \n sideEffects.push({\n type: 'neural',\n action: 'train',\n data: {\n patterns: [pattern],\n modelId: `workflow-optimizer-${workflowId}`,\n },\n });\n }\n \n // Generate improvement suggestions\n const improvements = await generateImprovementSuggestions(\n workflowId,\n state,\n performance,\n learnings,\n context\n );\n \n if (improvements.length > 0) {\n sideEffects.push({\n type: 'notification',\n action: 'emit',\n data: {\n event: 'workflow:improvements:suggested',\n data: {\n workflowId,\n improvements,\n performance,\n },\n },\n });\n }\n \n // Update workflow metrics\n sideEffects.push(\n {\n type: 'metric',\n action: 'update',\n data: {\n name: `workflow.completion.rate.${workflowId}`,\n value: performance.success ? 1 : 0,\n },\n },\n {\n type: 'metric',\n action: 'update',\n data: {\n name: `workflow.performance.score.${workflowId}`,\n value: performance.score,\n },\n }\n );\n \n return {\n continue: true,\n sideEffects,\n };\n },\n};\n\n// ===== Workflow Error Hook =====\n\nexport const workflowErrorHook = {\n id: 'agentic-workflow-error',\n type: 'workflow-error' as const,\n priority: 95,\n handler: async (\n payload: WorkflowHookPayload,\n context: AgenticHookContext\n ): Promise<HookHandlerResult> => {\n const { workflowId, error, state } = payload;\n \n if (!error) {\n return { continue: true };\n }\n \n const sideEffects: SideEffect[] = [];\n \n // Analyze error pattern\n const errorPattern = await analyzeErrorPattern(\n workflowId,\n error,\n state,\n context\n );\n \n // Store error for learning\n sideEffects.push({\n type: 'memory',\n action: 'store',\n data: {\n key: `error:${workflowId}:${Date.now()}`,\n value: {\n error: {\n message: error.message,\n stack: error.stack,\n type: error.name,\n },\n pattern: errorPattern,\n state: summarizeState(state),\n timestamp: Date.now(),\n },\n ttl: 604800, // 7 days\n },\n });\n \n // Check for recovery strategies\n const recovery = await findRecoveryStrategy(\n workflowId,\n error,\n errorPattern,\n context\n );\n \n if (recovery) {\n sideEffects.push({\n type: 'log',\n action: 'write',\n data: {\n level: 'info',\n message: 'Recovery strategy found',\n data: recovery,\n },\n });\n \n // Apply recovery\n const recoveredState = applyRecoveryStrategy(state, recovery);\n \n return {\n continue: true,\n modified: true,\n payload: {\n ...payload,\n state: recoveredState,\n error: undefined, // Clear error after recovery\n },\n sideEffects,\n };\n }\n \n // Learn from failure\n const failureLearning: Learning = {\n type: 'failure',\n context: `Error in workflow ${workflowId}: ${error.message}`,\n value: {\n errorType: error.name,\n state: summarizeState(state),\n pattern: errorPattern,\n },\n applicability: errorPattern.confidence,\n };\n \n sideEffects.push({\n type: 'memory',\n action: 'store',\n data: {\n key: `learning:failure:${workflowId}:${Date.now()}`,\n value: failureLearning,\n ttl: 0, // Permanent\n },\n });\n \n return {\n continue: true,\n sideEffects,\n };\n },\n};\n\n// ===== Helper Functions =====\n\nasync function loadWorkflowHistory(\n workflowId: string,\n context: AgenticHookContext\n): Promise<any[]> {\n const historyKey = `workflow:history:${workflowId}`;\n return await context.memory.cache.get(historyKey) || [];\n}\n\nasync function loadWorkflowLearnings(\n workflowId: string,\n context: AgenticHookContext\n): Promise<Learning[]> {\n const learningsKey = `workflow:learnings:${workflowId}`;\n return await context.memory.cache.get(learningsKey) || [];\n}\n\nasync function selectOptimalProvider(\n workflowId: string,\n state: any,\n history: any[],\n context: AgenticHookContext\n): Promise<string> {\n // Analyze historical performance by provider\n const providerStats = new Map<string, { success: number; total: number }>();\n \n for (const execution of history) {\n const provider = execution.provider;\n if (!provider) continue;\n \n const stats = providerStats.get(provider) || { success: 0, total: 0 };\n stats.total++;\n if (execution.success) stats.success++;\n providerStats.set(provider, stats);\n }\n \n // Calculate success rates\n let bestProvider = 'openai'; // Default\n let bestRate = 0;\n \n for (const [provider, stats] of providerStats) {\n const rate = stats.success / stats.total;\n if (rate > bestRate && stats.total >= 5) {\n bestRate = rate;\n bestProvider = provider;\n }\n }\n \n // Check current provider health\n const healthKey = `provider:health:${bestProvider}`;\n const health = await context.memory.cache.get(healthKey);\n \n if (health && health.score < 0.5) {\n // Provider unhealthy, select alternative\n return selectAlternativeProvider(bestProvider, providerStats);\n }\n \n return bestProvider;\n}\n\nasync function generateWorkflowPredictions(\n workflowId: string,\n state: any,\n context: AgenticHookContext\n): Promise<any> {\n // Generate predictions for workflow execution\n const predictions = {\n estimatedDuration: 0,\n successProbability: 0.7,\n likelyBottlenecks: [],\n recommendedOptimizations: [],\n };\n \n // Load historical durations\n const history = await loadWorkflowHistory(workflowId, context);\n if (history.length > 0) {\n const durations = history\n .filter(h => h.duration)\n .map(h => h.duration);\n \n if (durations.length > 0) {\n predictions.estimatedDuration = \n durations.reduce((a, b) => a + b, 0) / durations.length;\n }\n \n const successes = history.filter(h => h.success).length;\n predictions.successProbability = successes / history.length;\n }\n \n return predictions;\n}\n\nasync function getStepOptimizations(\n workflowId: string,\n step: string,\n context: AgenticHookContext\n): Promise<any[]> {\n // Get optimizations for specific step\n const optKey = `optimizations:${workflowId}:${step}`;\n return await context.memory.cache.get(optKey) || [];\n}\n\nfunction applyStepOptimizations(\n state: any,\n optimizations: any[]\n): any {\n const optimizedState = { ...state };\n \n for (const opt of optimizations) {\n switch (opt.type) {\n case 'skip':\n if (opt.condition && opt.condition(state)) {\n optimizedState.skipSteps = [\n ...(optimizedState.skipSteps || []),\n opt.target,\n ];\n }\n break;\n \n case 'parallel':\n optimizedState.parallelSteps = [\n ...(optimizedState.parallelSteps || []),\n ...opt.steps,\n ];\n break;\n \n case 'cache':\n optimizedState.useCache = true;\n optimizedState.cacheKeys = [\n ...(optimizedState.cacheKeys || []),\n opt.key,\n ];\n break;\n }\n }\n \n return optimizedState;\n}\n\nfunction summarizeState(state: any): any {\n // Create summary of state for storage\n return {\n keys: Object.keys(state),\n size: JSON.stringify(state).length,\n hasError: !!state.error,\n provider: state.provider,\n timestamp: Date.now(),\n };\n}\n\nasync function getDecisionOutcomes(\n workflowId: string,\n decisionPoint: string,\n context: AgenticHookContext\n): Promise<any[]> {\n // Get historical outcomes for decision point\n const outcomeKey = `outcomes:${workflowId}:${decisionPoint}`;\n return await context.memory.cache.get(outcomeKey) || [];\n}\n\nfunction adjustDecisionConfidence(\n decision: WorkflowDecision,\n historicalOutcomes: any[]\n): WorkflowDecision {\n if (historicalOutcomes.length === 0) {\n return decision;\n }\n \n // Calculate success rate for selected option\n const relevantOutcomes = historicalOutcomes.filter(o => \n o.selected === decision.selected\n );\n \n if (relevantOutcomes.length === 0) {\n return decision;\n }\n \n const successRate = relevantOutcomes.filter(o => o.success).length / \n relevantOutcomes.length;\n \n // Adjust confidence based on historical success\n const adjustedConfidence = decision.confidence * 0.7 + successRate * 0.3;\n \n return {\n ...decision,\n confidence: adjustedConfidence,\n learnings: [\n ...decision.learnings,\n {\n type: 'success',\n context: `Historical success rate: ${(successRate * 100).toFixed(1)}%`,\n value: successRate,\n applicability: Math.min(relevantOutcomes.length / 10, 1),\n },\n ],\n };\n}\n\nasync function generateAlternativeDecisions(\n workflowId: string,\n decision: WorkflowDecision,\n state: any,\n context: AgenticHookContext\n): Promise<WorkflowDecision[]> {\n // Generate alternative decision paths\n const alternatives: WorkflowDecision[] = [];\n \n // Check each option not selected\n for (const option of decision.options) {\n if (option === decision.selected) continue;\n \n // Calculate alternative confidence\n const altConfidence = await calculateAlternativeConfidence(\n workflowId,\n decision.point,\n option,\n state,\n context\n );\n \n if (altConfidence > 0.5) {\n alternatives.push({\n ...decision,\n selected: option,\n confidence: altConfidence,\n reasoning: `Alternative path based on historical analysis`,\n });\n }\n }\n \n return alternatives;\n}\n\nfunction calculateWorkflowPerformance(\n state: any,\n metrics: any\n): any {\n const performance = {\n success: !state.error,\n score: 0,\n duration: metrics?.duration || 0,\n efficiency: 0,\n reliability: 0,\n };\n \n // Calculate performance score\n if (performance.success) {\n performance.score = 0.7; // Base success score\n \n // Adjust for duration\n if (metrics?.duration && state.predictions?.estimatedDuration) {\n const durationRatio = state.predictions.estimatedDuration / metrics.duration;\n performance.efficiency = Math.min(durationRatio, 1);\n performance.score += performance.efficiency * 0.2;\n }\n \n // Adjust for error rate\n if (metrics?.errorRate !== undefined) {\n performance.reliability = 1 - metrics.errorRate;\n performance.score += performance.reliability * 0.1;\n }\n }\n \n return performance;\n}\n\nasync function extractWorkflowLearnings(\n workflowId: string,\n state: any,\n performance: any,\n context: AgenticHookContext\n): Promise<Learning[]> {\n const learnings: Learning[] = [];\n \n // Learn from successful execution\n if (performance.success) {\n learnings.push({\n type: 'success',\n context: `Successful workflow execution with score ${performance.score}`,\n value: {\n provider: state.provider,\n duration: performance.duration,\n decisions: extractDecisions(state),\n },\n applicability: performance.score,\n });\n }\n \n // Learn from optimizations\n if (state.appliedOptimizations) {\n for (const opt of state.appliedOptimizations) {\n learnings.push({\n type: 'optimization',\n context: `Applied ${opt.type} optimization at ${opt.step}`,\n value: opt,\n applicability: 0.8,\n });\n }\n }\n \n return learnings;\n}\n\nfunction countDecisions(state: any): number {\n // Count decisions made during workflow\n return state.decisions?.length || 0;\n}\n\nasync function generateImprovementSuggestions(\n workflowId: string,\n state: any,\n performance: any,\n learnings: Learning[],\n context: AgenticHookContext\n): Promise<any[]> {\n const suggestions: any[] = [];\n \n // Suggest caching if repeated operations\n if (performance.duration > 5000) {\n suggestions.push({\n type: 'cache',\n target: 'frequent_operations',\n reason: 'Long execution time detected',\n expectedImprovement: '30-50% reduction in duration',\n });\n }\n \n // Suggest parallelization\n if (state.sequentialSteps?.length > 3) {\n suggestions.push({\n type: 'parallel',\n target: 'independent_steps',\n reason: 'Multiple sequential steps detected',\n expectedImprovement: '40-60% reduction in duration',\n });\n }\n \n // Suggest provider switch based on learnings\n const providerLearnings = learnings.filter(l => \n l.type === 'success' && l.value.provider\n );\n \n if (providerLearnings.length > 0) {\n const providerScores = new Map<string, number>();\n for (const learning of providerLearnings) {\n const provider = learning.value.provider;\n const score = providerScores.get(provider) || 0;\n providerScores.set(provider, score + learning.applicability);\n }\n \n const currentScore = providerScores.get(state.provider) || 0;\n for (const [provider, score] of providerScores) {\n if (score > currentScore * 1.2) {\n suggestions.push({\n type: 'provider',\n target: provider,\n reason: `${provider} shows better historical performance`,\n expectedImprovement: `${((score / currentScore - 1) * 100).toFixed(0)}% better reliability`,\n });\n }\n }\n }\n \n return suggestions;\n}\n\nasync function analyzeErrorPattern(\n workflowId: string,\n error: Error,\n state: any,\n context: AgenticHookContext\n): Promise<any> {\n // Analyze error to find patterns\n const pattern = {\n type: classifyError(error),\n confidence: 0.7,\n context: {\n step: state.currentStep,\n provider: state.provider,\n errorMessage: error.message,\n },\n };\n \n // Check for similar errors\n const errorHistory = await context.memory.cache.get(\n `errors:${workflowId}:${pattern.type}`\n ) || [];\n \n if (errorHistory.length > 5) {\n pattern.confidence = 0.9;\n pattern.context.recurring = true;\n pattern.context.occurrences = errorHistory.length;\n }\n \n return pattern;\n}\n\nasync function findRecoveryStrategy(\n workflowId: string,\n error: Error,\n errorPattern: any,\n context: AgenticHookContext\n): Promise<any | null> {\n // Find recovery strategy for error\n if (errorPattern.type === 'timeout') {\n return {\n type: 'retry',\n params: {\n maxRetries: 3,\n backoff: 'exponential',\n timeout: 30000,\n },\n };\n }\n \n if (errorPattern.type === 'rate_limit') {\n return {\n type: 'throttle',\n params: {\n delay: 1000,\n maxConcurrent: 1,\n },\n };\n }\n \n if (errorPattern.type === 'validation') {\n return {\n type: 'transform',\n params: {\n sanitize: true,\n validate: true,\n },\n };\n }\n \n return null;\n}\n\nfunction applyRecoveryStrategy(state: any, recovery: any): any {\n const recoveredState = { ...state };\n \n switch (recovery.type) {\n case 'retry':\n recoveredState.retryConfig = recovery.params;\n recoveredState.shouldRetry = true;\n break;\n \n case 'throttle':\n recoveredState.throttleConfig = recovery.params;\n recoveredState.throttled = true;\n break;\n \n case 'transform':\n recoveredState.transformConfig = recovery.params;\n recoveredState.needsTransform = true;\n break;\n }\n \n recoveredState.recoveryApplied = recovery;\n delete recoveredState.error; // Clear error state\n \n return recoveredState;\n}\n\nfunction selectAlternativeProvider(\n currentProvider: string,\n providerStats: Map<string, { success: number; total: number }>\n): string {\n // Select alternative provider based on stats\n let bestAlternative = 'anthropic'; // Default fallback\n let bestRate = 0;\n \n for (const [provider, stats] of providerStats) {\n if (provider === currentProvider) continue;\n \n const rate = stats.success / stats.total;\n if (rate > bestRate && stats.total >= 3) {\n bestRate = rate;\n bestAlternative = provider;\n }\n }\n \n return bestAlternative;\n}\n\nasync function calculateAlternativeConfidence(\n workflowId: string,\n decisionPoint: string,\n option: string,\n state: any,\n context: AgenticHookContext\n): Promise<number> {\n // Calculate confidence for alternative option\n const outcomeKey = `outcomes:${workflowId}:${decisionPoint}:${option}`;\n const outcomes = await context.memory.cache.get(outcomeKey) || [];\n \n if (outcomes.length === 0) {\n return 0.5; // Default confidence\n }\n \n const successRate = outcomes.filter((o: any) => o.success).length / \n outcomes.length;\n \n // Adjust for recency\n const recentOutcomes = outcomes.slice(-10);\n const recentSuccessRate = recentOutcomes.filter((o: any) => o.success).length / \n recentOutcomes.length;\n \n return successRate * 0.7 + recentSuccessRate * 0.3;\n}\n\nfunction extractDecisions(state: any): any[] {\n // Extract decisions from state\n return state.decisions || [];\n}\n\nfunction classifyError(error: Error): string {\n const message = error.message.toLowerCase();\n \n if (message.includes('timeout')) return 'timeout';\n if (message.includes('rate limit')) return 'rate_limit';\n if (message.includes('validation')) return 'validation';\n if (message.includes('network')) return 'network';\n if (message.includes('auth')) return 'authentication';\n \n return 'unknown';\n}\n\n// ===== Register Hooks =====\n\nexport function registerWorkflowHooks(): void {\n agenticHookManager.register(workflowStartHook);\n agenticHookManager.register(workflowStepHook);\n agenticHookManager.register(workflowDecisionHook);\n agenticHookManager.register(workflowCompleteHook);\n agenticHookManager.register(workflowErrorHook);\n}"],"names":["agenticHookManager","workflowStartHook","id","type","priority","handler","payload","context","workflowId","state","sideEffects","history","loadWorkflowHistory","learnings","loadWorkflowLearnings","provider","selectOptimalProvider","enhancedState","startTime","Date","now","slice","predictions","generateWorkflowPredictions","push","action","data","key","sessionId","value","ttl","name","continue","modified","workflowStepHook","step","stepStart","optimizations","getStepOptimizations","length","optimizedState","applyStepOptimizations","level","message","summarizeState","timestamp","workflowDecisionHook","decision","historicalOutcomes","getDecisionOutcomes","point","adjustedDecision","adjustDecisionConfidence","alternatives","generateAlternativeDecisions","bestAlternative","find","alt","confidence","event","original","suggested","selected","reasoning","workflowCompleteHook","metrics","performance","calculateWorkflowPerformance","extractWorkflowLearnings","learning","success","pattern","score","occurrences","duration","decisions","countDecisions","neural","patterns","add","modelId","improvements","generateImprovementSuggestions","workflowErrorHook","error","errorPattern","analyzeErrorPattern","stack","recovery","findRecoveryStrategy","recoveredState","applyRecoveryStrategy","undefined","failureLearning","errorType","applicability","historyKey","memory","cache","get","learningsKey","providerStats","Map","execution","stats","total","set","bestProvider","bestRate","rate","healthKey","health","selectAlternativeProvider","estimatedDuration","successProbability","likelyBottlenecks","recommendedOptimizations","durations","filter","h","map","reduce","a","b","successes","optKey","opt","condition","skipSteps","target","parallelSteps","steps","useCache","cacheKeys","keys","Object","size","JSON","stringify","hasError","decisionPoint","outcomeKey","relevantOutcomes","o","successRate","adjustedConfidence","toFixed","Math","min","option","options","altConfidence","calculateAlternativeConfidence","efficiency","reliability","durationRatio","errorRate","extractDecisions","appliedOptimizations","suggestions","reason","expectedImprovement","sequentialSteps","providerLearnings","l","providerScores","currentScore","classifyError","currentStep","errorMessage","errorHistory","recurring","params","maxRetries","backoff","timeout","delay","maxConcurrent","sanitize","validate","retryConfig","shouldRetry","throttleConfig","throttled","transformConfig","needsTransform","recoveryApplied","currentProvider","outcomes","recentOutcomes","recentSuccessRate","toLowerCase","includes","registerWorkflowHooks","register"],"mappings":"AAOA,SAASA,kBAAkB,QAAQ,oBAAoB;AAavD,OAAO,MAAMC,oBAAoB;IAC/BC,IAAI;IACJC,MAAM;IACNC,UAAU;IACVC,SAAS,OACPC,SACAC;QAEA,MAAM,EAAEC,UAAU,EAAEC,KAAK,EAAE,GAAGH;QAE9B,MAAMI,cAA4B,EAAE;QAGpC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AElC,OAAOA,MAAMkE,SAAS,IAAI,EAAE;AAC9B;AAEA,SAAS4F,cAAcnF,KAAY;IACjC,MAAMzC,UAAUyC,MAAMzC,OAAO,CAACoJ,WAAW;IAEzC,IAAIpJ,QAAQqJ,QAAQ,CAAC,YAAY,OAAO;IACxC,IAAIrJ,QAAQqJ,QAAQ,CAAC,eAAe,OAAO;IAC3C,IAAIrJ,QAAQqJ,QAAQ,CAAC,eAAe,OAAO;IAC3C,IAAIrJ,QAAQqJ,QAAQ,CAAC,YAAY,OAAO;IACxC,IAAIrJ,QAAQqJ,QAAQ,CAAC,SAAS,OAAO;IAErC,OAAO;AACT;AAIA,OAAO,SAASC;IACdjM,mBAAmBkM,QAAQ,CAACjM;IAC5BD,mBAAmBkM,QAAQ,CAAChK;IAC5BlC,mBAAmBkM,QAAQ,CAACpJ;IAC5B9C,mBAAmBkM,QAAQ,CAAClI;IAC5BhE,mBAAmBkM,QAAQ,CAAC/G;AAC9B"}
|
|
@@ -870,7 +870,7 @@ export class SwarmCoordinator extends EventEmitter {
|
|
|
870
870
|
calculateCapabilityMatch(agent, task) {
|
|
871
871
|
const requiredCapabilities = task.requirements.capabilities;
|
|
872
872
|
let matches = 0;
|
|
873
|
-
|
|
873
|
+
const total = requiredCapabilities.length;
|
|
874
874
|
for (const capability of requiredCapabilities){
|
|
875
875
|
if (this.agentHasCapability(agent, capability)) {
|
|
876
876
|
matches++;
|