snow-flow 1.1.76 → 1.1.78

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 (234) hide show
  1. package/.claude-flow/queen/queen-memory.db +0 -0
  2. package/CLAUDE.md +34 -5
  3. package/README.md +256 -384
  4. package/dist/agents/base-agent.d.ts +92 -0
  5. package/dist/agents/base-agent.d.ts.map +1 -0
  6. package/dist/agents/base-agent.js +228 -0
  7. package/dist/agents/base-agent.js.map +1 -0
  8. package/dist/agents/coordinator.d.ts +200 -0
  9. package/dist/agents/coordinator.d.ts.map +1 -0
  10. package/dist/agents/coordinator.js +775 -0
  11. package/dist/agents/coordinator.js.map +1 -0
  12. package/dist/agents/flow-builder-agent.d.ts +18 -0
  13. package/dist/agents/flow-builder-agent.d.ts.map +1 -0
  14. package/dist/agents/flow-builder-agent.js +536 -0
  15. package/dist/agents/flow-builder-agent.js.map +1 -0
  16. package/dist/agents/index.d.ts +18 -0
  17. package/dist/agents/index.d.ts.map +1 -0
  18. package/dist/agents/index.js +61 -0
  19. package/dist/agents/index.js.map +1 -0
  20. package/dist/agents/queen-agent-example.d.ts +23 -0
  21. package/dist/agents/queen-agent-example.d.ts.map +1 -0
  22. package/dist/agents/queen-agent-example.js +241 -0
  23. package/dist/agents/queen-agent-example.js.map +1 -0
  24. package/dist/agents/queen-agent.d.ts +180 -0
  25. package/dist/agents/queen-agent.d.ts.map +1 -0
  26. package/dist/agents/queen-agent.js +909 -0
  27. package/dist/agents/queen-agent.js.map +1 -0
  28. package/dist/agents/queen-agent.test.d.ts +6 -0
  29. package/dist/agents/queen-agent.test.d.ts.map +1 -0
  30. package/dist/agents/queen-agent.test.js.map +1 -0
  31. package/dist/agents/script-writer-agent.d.ts +22 -0
  32. package/dist/agents/script-writer-agent.d.ts.map +1 -0
  33. package/dist/agents/script-writer-agent.js +695 -0
  34. package/dist/agents/script-writer-agent.js.map +1 -0
  35. package/dist/agents/security-agent.d.ts +23 -0
  36. package/dist/agents/security-agent.d.ts.map +1 -0
  37. package/dist/agents/security-agent.js +619 -0
  38. package/dist/agents/security-agent.js.map +1 -0
  39. package/dist/agents/test-agent.d.ts +26 -0
  40. package/dist/agents/test-agent.d.ts.map +1 -0
  41. package/dist/agents/test-agent.js +735 -0
  42. package/dist/agents/test-agent.js.map +1 -0
  43. package/dist/agents/test-agents.d.ts +7 -0
  44. package/dist/agents/test-agents.d.ts.map +1 -0
  45. package/dist/agents/test-agents.js +65 -0
  46. package/dist/agents/test-agents.js.map +1 -0
  47. package/dist/agents/widget-creator-agent.d.ts +18 -0
  48. package/dist/agents/widget-creator-agent.d.ts.map +1 -0
  49. package/dist/agents/widget-creator-agent.js +440 -0
  50. package/dist/agents/widget-creator-agent.js.map +1 -0
  51. package/dist/cli/snow-flow-cli-integration.d.ts +30 -0
  52. package/dist/cli/snow-flow-cli-integration.d.ts.map +1 -0
  53. package/dist/cli/snow-flow-cli-integration.js +385 -0
  54. package/dist/cli/snow-flow-cli-integration.js.map +1 -0
  55. package/dist/cli.js +466 -150
  56. package/dist/cli.js.map +1 -1
  57. package/dist/config/snow-flow-config.d.ts +1454 -0
  58. package/dist/config/snow-flow-config.d.ts.map +1 -0
  59. package/dist/config/snow-flow-config.js +403 -0
  60. package/dist/config/snow-flow-config.js.map +1 -0
  61. package/dist/health/system-health.d.ts +123 -0
  62. package/dist/health/system-health.d.ts.map +1 -0
  63. package/dist/health/system-health.js +580 -0
  64. package/dist/health/system-health.js.map +1 -0
  65. package/dist/index.d.ts +12 -1
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +19 -3
  68. package/dist/index.js.map +1 -1
  69. package/dist/mcp/servicenow-deployment-mcp-refactored.d.ts +58 -0
  70. package/dist/mcp/servicenow-deployment-mcp-refactored.d.ts.map +1 -0
  71. package/dist/mcp/servicenow-deployment-mcp-refactored.js +651 -0
  72. package/dist/mcp/servicenow-deployment-mcp-refactored.js.map +1 -0
  73. package/dist/mcp/servicenow-intelligent-mcp-refactored.d.ts +43 -0
  74. package/dist/mcp/servicenow-intelligent-mcp-refactored.d.ts.map +1 -0
  75. package/dist/mcp/servicenow-intelligent-mcp-refactored.js +576 -0
  76. package/dist/mcp/servicenow-intelligent-mcp-refactored.js.map +1 -0
  77. package/dist/mcp/servicenow-intelligent-mcp.d.ts +102 -1
  78. package/dist/mcp/servicenow-intelligent-mcp.d.ts.map +1 -1
  79. package/dist/mcp/servicenow-intelligent-mcp.js +2 -0
  80. package/dist/mcp/servicenow-intelligent-mcp.js.map +1 -1
  81. package/dist/mcp/shared/agent-context-provider.d.ts +77 -0
  82. package/dist/mcp/shared/agent-context-provider.d.ts.map +1 -0
  83. package/dist/mcp/shared/agent-context-provider.js +292 -0
  84. package/dist/mcp/shared/agent-context-provider.js.map +1 -0
  85. package/dist/mcp/shared/base-mcp-server.d.ts +97 -0
  86. package/dist/mcp/shared/base-mcp-server.d.ts.map +1 -0
  87. package/dist/mcp/shared/base-mcp-server.js +216 -0
  88. package/dist/mcp/shared/base-mcp-server.js.map +1 -0
  89. package/dist/mcp/shared/mcp-memory-manager.d.ts +87 -0
  90. package/dist/mcp/shared/mcp-memory-manager.d.ts.map +1 -0
  91. package/dist/mcp/shared/mcp-memory-manager.js +423 -0
  92. package/dist/mcp/shared/mcp-memory-manager.js.map +1 -0
  93. package/dist/memory/index.d.ts +9 -0
  94. package/dist/memory/index.d.ts.map +1 -0
  95. package/dist/memory/index.js +20 -0
  96. package/dist/memory/index.js.map +1 -0
  97. package/dist/memory/mcp-integration-example.d.ts +6 -0
  98. package/dist/memory/mcp-integration-example.d.ts.map +1 -0
  99. package/dist/memory/mcp-integration-example.js +282 -0
  100. package/dist/memory/mcp-integration-example.js.map +1 -0
  101. package/dist/memory/memory-client.d.ts +184 -0
  102. package/dist/memory/memory-client.d.ts.map +1 -0
  103. package/dist/memory/memory-client.js +325 -0
  104. package/dist/memory/memory-client.js.map +1 -0
  105. package/dist/memory/memory-operations.d.ts +170 -0
  106. package/dist/memory/memory-operations.d.ts.map +1 -0
  107. package/dist/memory/memory-operations.js +639 -0
  108. package/dist/memory/memory-operations.js.map +1 -0
  109. package/dist/memory/memory-system.d.ts +118 -0
  110. package/dist/memory/memory-system.d.ts.map +1 -0
  111. package/dist/memory/memory-system.js +477 -0
  112. package/dist/memory/memory-system.js.map +1 -0
  113. package/dist/memory/memory-test.d.ts +6 -0
  114. package/dist/memory/memory-test.d.ts.map +1 -0
  115. package/dist/memory/memory-test.js +162 -0
  116. package/dist/memory/memory-test.js.map +1 -0
  117. package/dist/memory/swarm-memory.d.ts +135 -0
  118. package/dist/memory/swarm-memory.d.ts.map +1 -0
  119. package/dist/memory/swarm-memory.js +378 -0
  120. package/dist/memory/swarm-memory.js.map +1 -0
  121. package/dist/monitoring/performance-tracker.d.ts +157 -0
  122. package/dist/monitoring/performance-tracker.d.ts.map +1 -0
  123. package/dist/monitoring/performance-tracker.js +571 -0
  124. package/dist/monitoring/performance-tracker.js.map +1 -0
  125. package/dist/queen/agent-factory.d.ts +3 -0
  126. package/dist/queen/agent-factory.d.ts.map +1 -1
  127. package/dist/queen/agent-factory.js +52 -0
  128. package/dist/queen/agent-factory.js.map +1 -1
  129. package/dist/queen/queen-memory.d.ts +8 -2
  130. package/dist/queen/queen-memory.d.ts.map +1 -1
  131. package/dist/queen/queen-memory.js +46 -4
  132. package/dist/queen/queen-memory.js.map +1 -1
  133. package/dist/snow-flow-system.d.ts +132 -0
  134. package/dist/snow-flow-system.d.ts.map +1 -0
  135. package/dist/snow-flow-system.js +396 -0
  136. package/dist/snow-flow-system.js.map +1 -0
  137. package/dist/types/todo.types.d.ts +61 -0
  138. package/dist/types/todo.types.d.ts.map +1 -0
  139. package/dist/types/todo.types.js +7 -0
  140. package/dist/types/todo.types.js.map +1 -0
  141. package/dist/utils/error-recovery.d.ts +101 -0
  142. package/dist/utils/error-recovery.d.ts.map +1 -0
  143. package/dist/utils/error-recovery.js +548 -0
  144. package/dist/utils/error-recovery.js.map +1 -0
  145. package/dist/version.d.ts +1 -1
  146. package/dist/version.js +1 -1
  147. package/package.json +7 -2
  148. package/deploy.sh +0 -366
  149. package/docker/base/Dockerfile.base +0 -45
  150. package/docker/generate-services.js +0 -244
  151. package/docker/nginx/Dockerfile +0 -71
  152. package/docker/nginx/consul-template.hcl +0 -64
  153. package/docker/nginx/healthcheck.sh +0 -178
  154. package/docker/nginx/nginx.conf +0 -210
  155. package/docker/nginx/supervisord.conf +0 -57
  156. package/docker/nginx/templates/upstreams.conf.tpl +0 -48
  157. package/docker/services/automation-mcp/Dockerfile +0 -32
  158. package/docker/services/automation-mcp/config/service.json +0 -28
  159. package/docker/services/automation-mcp/entrypoint.js +0 -51
  160. package/docker/services/deployment-mcp/Dockerfile +0 -32
  161. package/docker/services/deployment-mcp/entrypoint.js +0 -51
  162. package/docker/services/flow-composer-mcp/Dockerfile +0 -32
  163. package/docker/services/flow-composer-mcp/config/service.json +0 -28
  164. package/docker/services/flow-composer-mcp/entrypoint.js +0 -51
  165. package/docker/services/graph-memory-mcp/Dockerfile +0 -32
  166. package/docker/services/graph-memory-mcp/config/service.json +0 -28
  167. package/docker/services/graph-memory-mcp/entrypoint.js +0 -51
  168. package/docker/services/integration-mcp/Dockerfile +0 -32
  169. package/docker/services/integration-mcp/config/service.json +0 -28
  170. package/docker/services/integration-mcp/entrypoint.js +0 -51
  171. package/docker/services/intelligent-mcp/Dockerfile +0 -32
  172. package/docker/services/intelligent-mcp/config/service.json +0 -28
  173. package/docker/services/intelligent-mcp/entrypoint.js +0 -51
  174. package/docker/services/operations-mcp/Dockerfile +0 -32
  175. package/docker/services/operations-mcp/config/service.json +0 -28
  176. package/docker/services/operations-mcp/entrypoint.js +0 -51
  177. package/docker/services/platform-development-mcp/Dockerfile +0 -32
  178. package/docker/services/platform-development-mcp/config/service.json +0 -28
  179. package/docker/services/platform-development-mcp/entrypoint.js +0 -51
  180. package/docker/services/reporting-analytics-mcp/Dockerfile +0 -32
  181. package/docker/services/reporting-analytics-mcp/config/service.json +0 -28
  182. package/docker/services/reporting-analytics-mcp/entrypoint.js +0 -51
  183. package/docker/services/security-compliance-mcp/Dockerfile +0 -32
  184. package/docker/services/security-compliance-mcp/config/service.json +0 -28
  185. package/docker/services/security-compliance-mcp/entrypoint.js +0 -51
  186. package/docker/services/update-set-mcp/Dockerfile +0 -32
  187. package/docker/services/update-set-mcp/config/service.json +0 -28
  188. package/docker/services/update-set-mcp/entrypoint.js +0 -51
  189. package/docker-compose.override.yml +0 -132
  190. package/docker-compose.prod.yml +0 -340
  191. package/docker-compose.yml +0 -579
  192. package/k8s/automation-mcp.yaml +0 -232
  193. package/k8s/configmap.yaml +0 -237
  194. package/k8s/deployment-mcp.yaml +0 -232
  195. package/k8s/flow-composer-mcp.yaml +0 -232
  196. package/k8s/generate-k8s-manifests.js +0 -453
  197. package/k8s/graph-memory-mcp.yaml +0 -232
  198. package/k8s/infrastructure.yaml +0 -456
  199. package/k8s/ingress.yaml +0 -361
  200. package/k8s/integration-mcp.yaml +0 -232
  201. package/k8s/intelligent-mcp.yaml +0 -232
  202. package/k8s/kustomization.yaml +0 -111
  203. package/k8s/mcp-services.yaml +0 -2552
  204. package/k8s/monitoring.yaml +0 -515
  205. package/k8s/namespace.yaml +0 -80
  206. package/k8s/operations-mcp.yaml +0 -232
  207. package/k8s/platform-development-mcp.yaml +0 -232
  208. package/k8s/rbac.yaml +0 -140
  209. package/k8s/reporting-analytics-mcp.yaml +0 -232
  210. package/k8s/security-compliance-mcp.yaml +0 -232
  211. package/k8s/update-set-mcp.yaml +0 -232
  212. package/test-clean-install/.claude/config.json +0 -12
  213. package/test-clean-install/.env.example +0 -49
  214. package/test-clean-install/CLAUDE.md +0 -26
  215. package/test-clean-install/README.md +0 -23
  216. package/test-global-install/.claude/config.json +0 -12
  217. package/test-global-install/CLAUDE.md +0 -26
  218. package/test-global-install/README.md +0 -23
  219. package/test-global-install/test-global-install/.claude/config.json +0 -12
  220. package/test-global-install/test-global-install/CLAUDE.md +0 -26
  221. package/test-global-install/test-global-install/README.md +0 -23
  222. package/test-global-install/test-global-install/test-global-install/.claude/config.json +0 -12
  223. package/test-global-install/test-global-install/test-global-install/.env.example +0 -49
  224. package/test-global-install/test-global-install/test-global-install/CLAUDE.md +0 -26
  225. package/test-global-install/test-global-install/test-global-install/README.md +0 -23
  226. package/test-init-debug/.claude/config.json +0 -12
  227. package/test-init-debug/CLAUDE.md +0 -693
  228. package/test-init-debug/README.md +0 -392
  229. package/test-init-real/.claude/config.json +0 -12
  230. package/test-init-real/.claude/mcp-config.json +0 -128
  231. package/test-init-real/.claude/settings.json +0 -37
  232. package/test-init-real/CLAUDE.md +0 -693
  233. package/test-init-real/README.md +0 -392
  234. package/test-init-real/activate-mcp.sh +0 -15
@@ -0,0 +1,909 @@
1
+ "use strict";
2
+ /**
3
+ * Queen Agent Core
4
+ * Master coordinator that analyzes objectives and spawns specialized agents
5
+ * Works through Claude Code interface using TodoWrite for task coordination
6
+ */
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.QueenAgent = void 0;
42
+ const eventemitter3_1 = require("eventemitter3");
43
+ const queen_memory_1 = require("../queen/queen-memory");
44
+ const coordinator_1 = require("./coordinator");
45
+ const crypto = __importStar(require("crypto"));
46
+ class QueenAgent extends eventemitter3_1.EventEmitter {
47
+ constructor(config = {}) {
48
+ super();
49
+ this.config = {
50
+ memoryPath: config.memoryPath,
51
+ maxConcurrentAgents: config.maxConcurrentAgents || 8,
52
+ debugMode: config.debugMode || false,
53
+ autoSpawn: config.autoSpawn !== false,
54
+ claudeCodeInterface: config.claudeCodeInterface !== false
55
+ };
56
+ // Initialize core systems
57
+ this.memory = new queen_memory_1.QueenMemorySystem(this.config.memoryPath);
58
+ this.coordinator = new coordinator_1.AgentCoordinator(this.memory);
59
+ this.activeObjectives = new Map();
60
+ this.todoCoordinations = new Map();
61
+ this.activeAgents = new Map();
62
+ this.setupEventHandlers();
63
+ if (this.config.debugMode) {
64
+ console.log('👑 Queen Agent initialized with Claude Code interface');
65
+ }
66
+ }
67
+ /**
68
+ * Analyze objective and create coordinated execution plan
69
+ */
70
+ async analyzeObjective(objective) {
71
+ const queenObjective = typeof objective === 'string'
72
+ ? { id: this.generateId('obj'), description: objective }
73
+ : objective;
74
+ this.activeObjectives.set(queenObjective.id, queenObjective);
75
+ this.emit('objective:analyzing', queenObjective);
76
+ try {
77
+ // Analyze objective using memory patterns and neural learning
78
+ const analysis = await this.performObjectiveAnalysis(queenObjective);
79
+ // Store analysis in memory for coordination
80
+ await this.memory.store(`analysis_${queenObjective.id}`, {
81
+ objective: queenObjective,
82
+ analysis,
83
+ timestamp: new Date().toISOString()
84
+ });
85
+ // Create TodoWrite coordination structure
86
+ const todoCoordination = await this.createTodoCoordination(queenObjective, analysis);
87
+ this.todoCoordinations.set(queenObjective.id, todoCoordination);
88
+ this.emit('objective:analyzed', { objective: queenObjective, analysis, todos: todoCoordination.todos });
89
+ return analysis;
90
+ }
91
+ catch (error) {
92
+ this.emit('objective:error', { objective: queenObjective, error });
93
+ throw error;
94
+ }
95
+ }
96
+ /**
97
+ * Spawn agents based on objective requirements
98
+ */
99
+ async spawnAgents(objectiveId) {
100
+ const todoCoordination = this.todoCoordinations.get(objectiveId);
101
+ if (!todoCoordination) {
102
+ throw new Error(`No todo coordination found for objective: ${objectiveId}`);
103
+ }
104
+ const analysis = await this.memory.get(`analysis_${objectiveId}`);
105
+ if (!analysis) {
106
+ throw new Error(`No analysis found for objective: ${objectiveId}`);
107
+ }
108
+ const agents = [];
109
+ const requiredAgentTypes = new Set(analysis.analysis.requiredAgents);
110
+ // Spawn agents for each required type
111
+ for (const agentType of requiredAgentTypes) {
112
+ const agent = await this.spawnSpecializedAgent(agentType, objectiveId);
113
+ agents.push(agent);
114
+ this.activeAgents.set(agent.id, agent);
115
+ // Assign todos to agent based on capabilities
116
+ this.assignTodosToAgent(agent, todoCoordination);
117
+ }
118
+ // Update memory with agent spawning information
119
+ await this.memory.store(`agents_${objectiveId}`, {
120
+ agents: agents.map(a => ({ id: a.id, type: a.type, capabilities: a.capabilities })),
121
+ timestamp: new Date().toISOString()
122
+ });
123
+ this.emit('agents:spawned', { objectiveId, agents });
124
+ return agents;
125
+ }
126
+ /**
127
+ * Monitor and coordinate agent progress
128
+ */
129
+ async monitorProgress(objectiveId) {
130
+ const todoCoordination = this.todoCoordinations.get(objectiveId);
131
+ if (!todoCoordination) {
132
+ throw new Error(`No todo coordination found for objective: ${objectiveId}`);
133
+ }
134
+ // Calculate progress from todos
135
+ const completedTodos = todoCoordination.todos.filter(t => t.status === 'completed').length;
136
+ const totalTodos = todoCoordination.todos.length;
137
+ const overallProgress = totalTodos > 0 ? (completedTodos / totalTodos) * 100 : 0;
138
+ // Calculate per-agent progress
139
+ const byAgent = new Map();
140
+ for (const [todoId, agentId] of todoCoordination.agentAssignments) {
141
+ const agentTodos = Array.from(todoCoordination.agentAssignments.entries())
142
+ .filter(([_, aid]) => aid === agentId);
143
+ const agentCompleted = agentTodos.filter(([tid, _]) => todoCoordination.todos.find(t => t.id === tid)?.status === 'completed').length;
144
+ const agentProgress = agentTodos.length > 0 ? (agentCompleted / agentTodos.length) * 100 : 0;
145
+ byAgent.set(agentId, agentProgress);
146
+ }
147
+ // Identify blocking issues
148
+ const blockingIssues = await this.identifyBlockingIssues(todoCoordination);
149
+ // Estimate completion based on current velocity
150
+ const estimatedCompletion = this.estimateCompletion(todoCoordination, overallProgress);
151
+ // Store progress in memory
152
+ await this.memory.store(`progress_${objectiveId}`, {
153
+ overall: overallProgress,
154
+ byAgent: Object.fromEntries(byAgent),
155
+ blockingIssues,
156
+ estimatedCompletion: estimatedCompletion.toISOString(),
157
+ timestamp: new Date().toISOString()
158
+ });
159
+ this.emit('progress:updated', { objectiveId, overall: overallProgress, byAgent, blockingIssues });
160
+ return {
161
+ overall: overallProgress,
162
+ byAgent,
163
+ blockingIssues,
164
+ estimatedCompletion
165
+ };
166
+ }
167
+ /**
168
+ * Make memory-driven decisions based on past patterns
169
+ */
170
+ async makeDecision(context) {
171
+ // Query memory for similar past decisions
172
+ const similarPatterns = await this.memory.findSimilarPatterns(context.objective);
173
+ // Analyze success rates of different approaches
174
+ const optionScores = new Map();
175
+ for (const option of context.options) {
176
+ const score = this.calculateOptionScore(option, similarPatterns, context);
177
+ optionScores.set(option, score);
178
+ }
179
+ // Select best option
180
+ const bestOption = Array.from(optionScores.entries())
181
+ .sort((a, b) => b[1] - a[1])[0];
182
+ const decision = {
183
+ decision: bestOption[0],
184
+ reasoning: this.generateDecisionReasoning(bestOption[0], similarPatterns, context),
185
+ confidence: bestOption[1] / 100
186
+ };
187
+ // Store decision for future learning
188
+ await this.memory.storeDecision({
189
+ context,
190
+ decision: decision.decision,
191
+ confidence: decision.confidence,
192
+ timestamp: new Date().toISOString()
193
+ });
194
+ this.emit('decision:made', decision);
195
+ return decision;
196
+ }
197
+ /**
198
+ * Create TodoWrite coordination structure
199
+ */
200
+ async createTodoCoordination(objective, analysis) {
201
+ const todos = [];
202
+ const dependencies = new Map();
203
+ // Create high-level todos based on task analysis
204
+ if (analysis.type === 'widget') {
205
+ todos.push(...this.createWidgetTodos(objective, analysis));
206
+ }
207
+ else if (analysis.type === 'flow') {
208
+ todos.push(...this.createFlowTodos(objective, analysis));
209
+ }
210
+ else if (analysis.type === 'script') {
211
+ todos.push(...this.createScriptTodos(objective, analysis));
212
+ }
213
+ else if (analysis.type === 'integration') {
214
+ todos.push(...this.createIntegrationTodos(objective, analysis));
215
+ }
216
+ else {
217
+ todos.push(...this.createGenericTodos(objective, analysis));
218
+ }
219
+ // Set up dependencies based on logical flow
220
+ this.setupTodoDependencies(todos, dependencies);
221
+ return {
222
+ taskId: objective.id,
223
+ todos,
224
+ agentAssignments: new Map(),
225
+ dependencies
226
+ };
227
+ }
228
+ /**
229
+ * Create widget-specific todos
230
+ */
231
+ createWidgetTodos(objective, analysis) {
232
+ const todos = [
233
+ {
234
+ id: this.generateId('todo'),
235
+ content: `Analyze widget requirements: ${objective.description}`,
236
+ status: 'pending',
237
+ priority: 'high'
238
+ },
239
+ {
240
+ id: this.generateId('todo'),
241
+ content: 'Design widget HTML template structure',
242
+ status: 'pending',
243
+ priority: 'high'
244
+ },
245
+ {
246
+ id: this.generateId('todo'),
247
+ content: 'Implement server-side data processing logic',
248
+ status: 'pending',
249
+ priority: 'high'
250
+ },
251
+ {
252
+ id: this.generateId('todo'),
253
+ content: 'Create client-side controller script',
254
+ status: 'pending',
255
+ priority: 'medium'
256
+ },
257
+ {
258
+ id: this.generateId('todo'),
259
+ content: 'Style widget with responsive CSS',
260
+ status: 'pending',
261
+ priority: 'medium'
262
+ },
263
+ {
264
+ id: this.generateId('todo'),
265
+ content: 'Test widget functionality with mock data',
266
+ status: 'pending',
267
+ priority: 'medium'
268
+ },
269
+ {
270
+ id: this.generateId('todo'),
271
+ content: 'Deploy widget to ServiceNow instance',
272
+ status: 'pending',
273
+ priority: 'high'
274
+ },
275
+ {
276
+ id: this.generateId('todo'),
277
+ content: 'Validate deployment and run integration tests',
278
+ status: 'pending',
279
+ priority: 'high'
280
+ }
281
+ ];
282
+ return todos;
283
+ }
284
+ /**
285
+ * Create flow-specific todos
286
+ */
287
+ createFlowTodos(objective, analysis) {
288
+ const todos = [
289
+ {
290
+ id: this.generateId('todo'),
291
+ content: `Analyze flow requirements: ${objective.description}`,
292
+ status: 'pending',
293
+ priority: 'high'
294
+ },
295
+ {
296
+ id: this.generateId('todo'),
297
+ content: 'Design flow trigger conditions and events',
298
+ status: 'pending',
299
+ priority: 'high'
300
+ },
301
+ {
302
+ id: this.generateId('todo'),
303
+ content: 'Map out flow steps and decision points',
304
+ status: 'pending',
305
+ priority: 'high'
306
+ },
307
+ {
308
+ id: this.generateId('todo'),
309
+ content: 'Configure flow actions and integrations',
310
+ status: 'pending',
311
+ priority: 'medium'
312
+ },
313
+ {
314
+ id: this.generateId('todo'),
315
+ content: 'Set up data transformations and variables',
316
+ status: 'pending',
317
+ priority: 'medium'
318
+ },
319
+ {
320
+ id: this.generateId('todo'),
321
+ content: 'Create flow using natural language API',
322
+ status: 'pending',
323
+ priority: 'high'
324
+ },
325
+ {
326
+ id: this.generateId('todo'),
327
+ content: 'Test flow with mock scenarios',
328
+ status: 'pending',
329
+ priority: 'high'
330
+ },
331
+ {
332
+ id: this.generateId('todo'),
333
+ content: 'Deploy and activate flow',
334
+ status: 'pending',
335
+ priority: 'high'
336
+ }
337
+ ];
338
+ return todos;
339
+ }
340
+ /**
341
+ * Create script-specific todos
342
+ */
343
+ createScriptTodos(objective, analysis) {
344
+ const todos = [
345
+ {
346
+ id: this.generateId('todo'),
347
+ content: `Analyze script requirements: ${objective.description}`,
348
+ status: 'pending',
349
+ priority: 'high'
350
+ },
351
+ {
352
+ id: this.generateId('todo'),
353
+ content: 'Determine script type (Business Rule, Script Include, etc.)',
354
+ status: 'pending',
355
+ priority: 'high'
356
+ },
357
+ {
358
+ id: this.generateId('todo'),
359
+ content: 'Design script logic and error handling',
360
+ status: 'pending',
361
+ priority: 'high'
362
+ },
363
+ {
364
+ id: this.generateId('todo'),
365
+ content: 'Implement core business logic',
366
+ status: 'pending',
367
+ priority: 'high'
368
+ },
369
+ {
370
+ id: this.generateId('todo'),
371
+ content: 'Add logging and debugging capabilities',
372
+ status: 'pending',
373
+ priority: 'medium'
374
+ },
375
+ {
376
+ id: this.generateId('todo'),
377
+ content: 'Create unit tests for script functions',
378
+ status: 'pending',
379
+ priority: 'medium'
380
+ },
381
+ {
382
+ id: this.generateId('todo'),
383
+ content: 'Deploy script to ServiceNow',
384
+ status: 'pending',
385
+ priority: 'high'
386
+ },
387
+ {
388
+ id: this.generateId('todo'),
389
+ content: 'Validate script execution and performance',
390
+ status: 'pending',
391
+ priority: 'high'
392
+ }
393
+ ];
394
+ return todos;
395
+ }
396
+ /**
397
+ * Create integration-specific todos
398
+ */
399
+ createIntegrationTodos(objective, analysis) {
400
+ const todos = [
401
+ {
402
+ id: this.generateId('todo'),
403
+ content: `Analyze integration requirements: ${objective.description}`,
404
+ status: 'pending',
405
+ priority: 'high'
406
+ },
407
+ {
408
+ id: this.generateId('todo'),
409
+ content: 'Identify external systems and APIs',
410
+ status: 'pending',
411
+ priority: 'high'
412
+ },
413
+ {
414
+ id: this.generateId('todo'),
415
+ content: 'Design data mapping and transformation',
416
+ status: 'pending',
417
+ priority: 'high'
418
+ },
419
+ {
420
+ id: this.generateId('todo'),
421
+ content: 'Configure authentication and security',
422
+ status: 'pending',
423
+ priority: 'high'
424
+ },
425
+ {
426
+ id: this.generateId('todo'),
427
+ content: 'Create REST/SOAP message configurations',
428
+ status: 'pending',
429
+ priority: 'medium'
430
+ },
431
+ {
432
+ id: this.generateId('todo'),
433
+ content: 'Implement error handling and retry logic',
434
+ status: 'pending',
435
+ priority: 'medium'
436
+ },
437
+ {
438
+ id: this.generateId('todo'),
439
+ content: 'Test integration with mock endpoints',
440
+ status: 'pending',
441
+ priority: 'high'
442
+ },
443
+ {
444
+ id: this.generateId('todo'),
445
+ content: 'Deploy and monitor integration',
446
+ status: 'pending',
447
+ priority: 'high'
448
+ }
449
+ ];
450
+ return todos;
451
+ }
452
+ /**
453
+ * Create generic todos for unknown task types
454
+ */
455
+ createGenericTodos(objective, analysis) {
456
+ const todos = [
457
+ {
458
+ id: this.generateId('todo'),
459
+ content: `Analyze requirements: ${objective.description}`,
460
+ status: 'pending',
461
+ priority: 'high'
462
+ },
463
+ {
464
+ id: this.generateId('todo'),
465
+ content: 'Research existing ServiceNow capabilities',
466
+ status: 'pending',
467
+ priority: 'high'
468
+ },
469
+ {
470
+ id: this.generateId('todo'),
471
+ content: 'Design solution architecture',
472
+ status: 'pending',
473
+ priority: 'high'
474
+ },
475
+ {
476
+ id: this.generateId('todo'),
477
+ content: 'Implement core functionality',
478
+ status: 'pending',
479
+ priority: 'high'
480
+ },
481
+ {
482
+ id: this.generateId('todo'),
483
+ content: 'Create necessary configurations',
484
+ status: 'pending',
485
+ priority: 'medium'
486
+ },
487
+ {
488
+ id: this.generateId('todo'),
489
+ content: 'Test solution thoroughly',
490
+ status: 'pending',
491
+ priority: 'high'
492
+ },
493
+ {
494
+ id: this.generateId('todo'),
495
+ content: 'Deploy to ServiceNow',
496
+ status: 'pending',
497
+ priority: 'high'
498
+ },
499
+ {
500
+ id: this.generateId('todo'),
501
+ content: 'Validate and document solution',
502
+ status: 'pending',
503
+ priority: 'medium'
504
+ }
505
+ ];
506
+ return todos;
507
+ }
508
+ /**
509
+ * Set up logical dependencies between todos
510
+ */
511
+ setupTodoDependencies(todos, dependencies) {
512
+ // For sequential tasks, each depends on the previous
513
+ for (let i = 1; i < todos.length; i++) {
514
+ dependencies.set(todos[i].id, [todos[i - 1].id]);
515
+ }
516
+ // Some tasks can be parallelized
517
+ // For example, styling and client script can happen in parallel after template is done
518
+ const templateTodo = todos.find(t => t.content.includes('template') || t.content.includes('structure'));
519
+ const stylingTodo = todos.find(t => t.content.includes('CSS') || t.content.includes('style'));
520
+ const clientTodo = todos.find(t => t.content.includes('client') || t.content.includes('controller'));
521
+ if (templateTodo && stylingTodo && clientTodo) {
522
+ // Both styling and client script depend only on template, not on each other
523
+ dependencies.set(stylingTodo.id, [templateTodo.id]);
524
+ dependencies.set(clientTodo.id, [templateTodo.id]);
525
+ }
526
+ }
527
+ /**
528
+ * Assign todos to agent based on capabilities
529
+ */
530
+ assignTodosToAgent(agent, todoCoordination) {
531
+ const agentCapabilityMap = {
532
+ 'widget-creator': ['widget', 'template', 'HTML', 'server', 'client', 'deploy widget'],
533
+ 'flow-builder': ['flow', 'trigger', 'decision', 'action', 'workflow'],
534
+ 'script-writer': ['script', 'business rule', 'logic', 'function'],
535
+ 'app-architect': ['architecture', 'design', 'structure', 'solution'],
536
+ 'integration-specialist': ['integration', 'REST', 'SOAP', 'API', 'external'],
537
+ 'catalog-manager': ['catalog', 'item', 'category', 'variable'],
538
+ 'researcher': ['analyze', 'research', 'requirements', 'existing'],
539
+ 'tester': ['test', 'validate', 'mock', 'scenario', 'integration test']
540
+ };
541
+ const agentKeywords = agentCapabilityMap[agent.type] || [];
542
+ // Assign todos that match agent capabilities
543
+ for (const todo of todoCoordination.todos) {
544
+ if (!todoCoordination.agentAssignments.has(todo.id)) {
545
+ const todoLower = todo.content.toLowerCase();
546
+ const matches = agentKeywords.some(keyword => todoLower.includes(keyword.toLowerCase()));
547
+ if (matches) {
548
+ todoCoordination.agentAssignments.set(todo.id, agent.id);
549
+ // Update agent task list
550
+ if (!agent.task) {
551
+ agent.task = todo.id;
552
+ }
553
+ }
554
+ }
555
+ }
556
+ }
557
+ /**
558
+ * Perform deep analysis of objective
559
+ */
560
+ async performObjectiveAnalysis(objective) {
561
+ const description = objective.description.toLowerCase();
562
+ // Determine task type
563
+ let type = 'unknown';
564
+ if (description.includes('widget'))
565
+ type = 'widget';
566
+ else if (description.includes('flow') || description.includes('workflow'))
567
+ type = 'flow';
568
+ else if (description.includes('script') || description.includes('business rule'))
569
+ type = 'script';
570
+ else if (description.includes('app') || description.includes('application'))
571
+ type = 'application';
572
+ else if (description.includes('integration') || description.includes('api'))
573
+ type = 'integration';
574
+ // Determine required agents
575
+ const requiredAgents = [];
576
+ // Always include researcher for analysis
577
+ requiredAgents.push('researcher');
578
+ // Add type-specific agents
579
+ switch (type) {
580
+ case 'widget':
581
+ requiredAgents.push('widget-creator');
582
+ if (description.includes('test'))
583
+ requiredAgents.push('tester');
584
+ break;
585
+ case 'flow':
586
+ requiredAgents.push('flow-builder');
587
+ if (description.includes('catalog'))
588
+ requiredAgents.push('catalog-manager');
589
+ if (description.includes('test'))
590
+ requiredAgents.push('tester');
591
+ break;
592
+ case 'script':
593
+ requiredAgents.push('script-writer');
594
+ if (description.includes('test'))
595
+ requiredAgents.push('tester');
596
+ break;
597
+ case 'integration':
598
+ requiredAgents.push('integration-specialist');
599
+ requiredAgents.push('tester');
600
+ break;
601
+ case 'application':
602
+ requiredAgents.push('app-architect');
603
+ requiredAgents.push('widget-creator');
604
+ requiredAgents.push('flow-builder');
605
+ requiredAgents.push('tester');
606
+ break;
607
+ default:
608
+ // For unknown types, spawn a balanced team
609
+ requiredAgents.push('app-architect');
610
+ requiredAgents.push('script-writer');
611
+ break;
612
+ }
613
+ // Estimate complexity based on description
614
+ const complexityFactors = {
615
+ words: description.split(' ').length,
616
+ hasIntegration: description.includes('integration') || description.includes('api'),
617
+ hasMultipleComponents: description.includes('and') || description.includes('with'),
618
+ hasComplexLogic: description.includes('complex') || description.includes('advanced'),
619
+ hasPerformanceReqs: description.includes('performance') || description.includes('optimize')
620
+ };
621
+ const estimatedComplexity = complexityFactors.words / 10 +
622
+ (complexityFactors.hasIntegration ? 2 : 0) +
623
+ (complexityFactors.hasMultipleComponents ? 1 : 0) +
624
+ (complexityFactors.hasComplexLogic ? 2 : 0) +
625
+ (complexityFactors.hasPerformanceReqs ? 1 : 0);
626
+ // Look for successful patterns in memory
627
+ const suggestedPattern = await this.memory.findBestPattern(type);
628
+ // Extract dependencies
629
+ const dependencies = [];
630
+ if (description.includes('table'))
631
+ dependencies.push('table_creation');
632
+ if (description.includes('user'))
633
+ dependencies.push('user_management');
634
+ if (description.includes('approval'))
635
+ dependencies.push('approval_framework');
636
+ if (description.includes('notification'))
637
+ dependencies.push('notification_system');
638
+ return {
639
+ type,
640
+ requiredAgents: [...new Set(requiredAgents)], // Remove duplicates
641
+ estimatedComplexity: Math.min(10, Math.max(1, estimatedComplexity)),
642
+ suggestedPattern,
643
+ dependencies
644
+ };
645
+ }
646
+ /**
647
+ * Spawn a specialized agent
648
+ */
649
+ async spawnSpecializedAgent(type, objectiveId) {
650
+ const agentId = this.generateId(`agent_${type}`);
651
+ const agent = {
652
+ id: agentId,
653
+ type,
654
+ status: 'idle',
655
+ capabilities: this.getAgentCapabilities(type),
656
+ mcpTools: this.getAgentMcpTools(type)
657
+ };
658
+ // Store agent in memory for coordination
659
+ await this.memory.store(`agent_${agentId}`, {
660
+ agent,
661
+ objectiveId,
662
+ spawnedAt: new Date().toISOString()
663
+ });
664
+ // Notify coordinator of new agent
665
+ await this.coordinator.registerAgent(agent);
666
+ this.emit('agent:spawned', agent);
667
+ return agent;
668
+ }
669
+ /**
670
+ * Get agent capabilities based on type
671
+ */
672
+ getAgentCapabilities(type) {
673
+ const capabilityMap = {
674
+ 'widget-creator': ['html_generation', 'css_styling', 'javascript_development', 'servicenow_api', 'widget_deployment'],
675
+ 'flow-builder': ['flow_design', 'trigger_configuration', 'action_creation', 'decision_logic', 'flow_testing'],
676
+ 'script-writer': ['glide_scripting', 'business_logic', 'error_handling', 'performance_optimization', 'script_deployment'],
677
+ 'app-architect': ['system_design', 'architecture_planning', 'component_integration', 'best_practices', 'documentation'],
678
+ 'integration-specialist': ['rest_api', 'soap_services', 'data_transformation', 'authentication', 'error_recovery'],
679
+ 'catalog-manager': ['catalog_creation', 'variable_management', 'workflow_linking', 'approval_setup', 'ui_design'],
680
+ 'researcher': ['requirement_analysis', 'feasibility_study', 'solution_research', 'best_practice_identification'],
681
+ 'tester': ['test_planning', 'test_execution', 'mock_data_creation', 'integration_testing', 'performance_testing']
682
+ };
683
+ return capabilityMap[type] || ['general_servicenow_development'];
684
+ }
685
+ /**
686
+ * Get MCP tools available to agent type
687
+ */
688
+ getAgentMcpTools(type) {
689
+ const toolMap = {
690
+ 'widget-creator': ['snow_deploy', 'snow_preview_widget', 'snow_widget_test'],
691
+ 'flow-builder': ['snow_create_flow', 'snow_test_flow_with_mock', 'snow_validate_flow_definition'],
692
+ 'script-writer': ['snow_create_script_include', 'snow_create_business_rule', 'snow_create_client_script'],
693
+ 'app-architect': ['snow_analyze_requirements', 'snow_create_application', 'snow_intelligent_flow_analysis'],
694
+ 'integration-specialist': ['snow_create_rest_message', 'snow_create_transform_map', 'snow_test_integration'],
695
+ 'catalog-manager': ['snow_catalog_item_search', 'snow_catalog_item_manager', 'snow_link_catalog_to_flow'],
696
+ 'researcher': ['snow_find_artifact', 'snow_comprehensive_search', 'snow_discover_existing_flows'],
697
+ 'tester': ['snow_test_flow_with_mock', 'snow_widget_test', 'snow_comprehensive_flow_test']
698
+ };
699
+ return toolMap[type] || ['snow_find_artifact'];
700
+ }
701
+ /**
702
+ * Identify blocking issues in todo coordination
703
+ */
704
+ async identifyBlockingIssues(todoCoordination) {
705
+ const issues = [];
706
+ // Check for todos with unmet dependencies
707
+ for (const [todoId, deps] of todoCoordination.dependencies) {
708
+ const todo = todoCoordination.todos.find(t => t.id === todoId);
709
+ if (todo && todo.status === 'pending') {
710
+ const unmetDeps = deps.filter(depId => {
711
+ const depTodo = todoCoordination.todos.find(t => t.id === depId);
712
+ return depTodo && depTodo.status !== 'completed';
713
+ });
714
+ if (unmetDeps.length > 0) {
715
+ issues.push(`Todo "${todo.content}" blocked by ${unmetDeps.length} dependencies`);
716
+ }
717
+ }
718
+ }
719
+ // Check for todos with no assigned agent
720
+ const unassignedTodos = todoCoordination.todos.filter(todo => !todoCoordination.agentAssignments.has(todo.id) && todo.status === 'pending');
721
+ if (unassignedTodos.length > 0) {
722
+ issues.push(`${unassignedTodos.length} todos have no assigned agent`);
723
+ }
724
+ // Check for failed todos
725
+ const failedTodos = todoCoordination.todos.filter(t => t.status === 'cancelled');
726
+ if (failedTodos.length > 0) {
727
+ issues.push(`${failedTodos.length} todos have failed`);
728
+ }
729
+ return issues;
730
+ }
731
+ /**
732
+ * Estimate completion time based on progress
733
+ */
734
+ estimateCompletion(todoCoordination, currentProgress) {
735
+ const startTime = new Date(todoCoordination.taskId.split('_')[1]); // Extract timestamp from ID
736
+ const elapsedMs = Date.now() - startTime.getTime();
737
+ if (currentProgress === 0) {
738
+ // Default estimate if no progress yet
739
+ return new Date(Date.now() + 3600000); // 1 hour
740
+ }
741
+ const estimatedTotalMs = (elapsedMs / currentProgress) * 100;
742
+ const remainingMs = estimatedTotalMs - elapsedMs;
743
+ return new Date(Date.now() + remainingMs);
744
+ }
745
+ /**
746
+ * Calculate score for decision option
747
+ */
748
+ calculateOptionScore(option, patterns, context) {
749
+ let score = 50; // Base score
750
+ // Adjust based on historical success with similar patterns
751
+ for (const pattern of patterns) {
752
+ if (pattern.agentSequence.some(agent => option.toLowerCase().includes(agent))) {
753
+ score += pattern.successRate * 20;
754
+ }
755
+ }
756
+ // Adjust based on context constraints
757
+ if (context.currentState?.failedAttempts?.includes(option)) {
758
+ score -= 30; // Penalize previously failed options
759
+ }
760
+ // Boost score if option matches objective keywords
761
+ const objectiveWords = context.objective.toLowerCase().split(' ');
762
+ const optionWords = option.toLowerCase().split(' ');
763
+ const matches = objectiveWords.filter(word => optionWords.includes(word)).length;
764
+ score += matches * 5;
765
+ return Math.min(100, Math.max(0, score));
766
+ }
767
+ /**
768
+ * Generate reasoning for decision
769
+ */
770
+ generateDecisionReasoning(decision, patterns, context) {
771
+ const reasons = [];
772
+ // Check historical patterns
773
+ const relevantPatterns = patterns.filter(p => p.agentSequence.some(agent => decision.toLowerCase().includes(agent)));
774
+ if (relevantPatterns.length > 0) {
775
+ const avgSuccess = relevantPatterns.reduce((sum, p) => sum + p.successRate, 0) / relevantPatterns.length;
776
+ reasons.push(`Historical success rate: ${Math.round(avgSuccess)}%`);
777
+ }
778
+ // Check objective alignment
779
+ const objectiveWords = context.objective.toLowerCase().split(' ');
780
+ const decisionWords = decision.toLowerCase().split(' ');
781
+ const alignment = objectiveWords.filter(word => decisionWords.includes(word)).length;
782
+ if (alignment > 0) {
783
+ reasons.push(`Strong alignment with objective (${alignment} matching concepts)`);
784
+ }
785
+ // Default reasoning if no specific reasons
786
+ if (reasons.length === 0) {
787
+ reasons.push('Best option based on current context and available capabilities');
788
+ }
789
+ return reasons.join('; ');
790
+ }
791
+ /**
792
+ * Set up event handlers for coordination
793
+ */
794
+ setupEventHandlers() {
795
+ // Listen to coordinator events
796
+ this.coordinator.on('agent:handoff', async (data) => {
797
+ await this.handleAgentHandoff(data);
798
+ });
799
+ this.coordinator.on('agent:blocked', async (data) => {
800
+ await this.handleAgentBlocked(data);
801
+ });
802
+ this.coordinator.on('coordination:error', async (error) => {
803
+ await this.handleCoordinationError(error);
804
+ });
805
+ }
806
+ /**
807
+ * Handle agent handoff events
808
+ */
809
+ async handleAgentHandoff(data) {
810
+ this.emit('coordination:handoff', data);
811
+ // Update todo status if handoff includes completed work
812
+ if (data.completedTodoId) {
813
+ await this.updateTodoStatus(data.objectiveId, data.completedTodoId, 'completed');
814
+ }
815
+ }
816
+ /**
817
+ * Handle agent blocked events
818
+ */
819
+ async handleAgentBlocked(data) {
820
+ this.emit('coordination:blocked', data);
821
+ // Attempt to resolve blockage
822
+ const resolution = await this.makeDecision({
823
+ objective: `Resolve blockage for ${data.agentId}`,
824
+ currentState: data,
825
+ options: ['spawn_helper_agent', 'reassign_task', 'provide_fallback', 'wait_for_dependency']
826
+ });
827
+ if (resolution.decision === 'spawn_helper_agent') {
828
+ // Spawn additional agent to help
829
+ await this.spawnAgents(data.objectiveId);
830
+ }
831
+ }
832
+ /**
833
+ * Handle coordination errors
834
+ */
835
+ async handleCoordinationError(error) {
836
+ this.emit('coordination:error', error);
837
+ // Log error to memory for learning
838
+ await this.memory.store(`error_${Date.now()}`, {
839
+ error: error.message,
840
+ stack: error.stack,
841
+ context: error.context,
842
+ timestamp: new Date().toISOString()
843
+ });
844
+ }
845
+ /**
846
+ * Update todo status
847
+ */
848
+ async updateTodoStatus(objectiveId, todoId, status) {
849
+ const todoCoordination = this.todoCoordinations.get(objectiveId);
850
+ if (!todoCoordination)
851
+ return;
852
+ const todo = todoCoordination.todos.find(t => t.id === todoId);
853
+ if (todo) {
854
+ todo.status = status;
855
+ // Store update in memory
856
+ await this.memory.store(`todo_update_${todoId}`, {
857
+ todoId,
858
+ newStatus: status,
859
+ timestamp: new Date().toISOString()
860
+ });
861
+ this.emit('todo:updated', { objectiveId, todoId, status });
862
+ }
863
+ }
864
+ /**
865
+ * Generate unique ID
866
+ */
867
+ generateId(prefix) {
868
+ return `${prefix}_${Date.now()}_${crypto.randomBytes(4).toString('hex')}`;
869
+ }
870
+ /**
871
+ * Get queen status
872
+ */
873
+ async getStatus() {
874
+ let totalTodos = 0;
875
+ let completedTodos = 0;
876
+ for (const coordination of this.todoCoordinations.values()) {
877
+ totalTodos += coordination.todos.length;
878
+ completedTodos += coordination.todos.filter(t => t.status === 'completed').length;
879
+ }
880
+ return {
881
+ activeObjectives: this.activeObjectives.size,
882
+ activeAgents: this.activeAgents.size,
883
+ totalTodos,
884
+ completedTodos,
885
+ memoryStats: await this.memory.getStats()
886
+ };
887
+ }
888
+ /**
889
+ * Shutdown queen agent
890
+ */
891
+ async shutdown() {
892
+ if (this.config.debugMode) {
893
+ console.log('👑 Shutting down Queen Agent');
894
+ }
895
+ // Terminate all active agents
896
+ for (const agent of this.activeAgents.values()) {
897
+ await this.coordinator.terminateAgent(agent.id);
898
+ }
899
+ // Close memory system
900
+ this.memory.close();
901
+ // Clear all maps
902
+ this.activeObjectives.clear();
903
+ this.todoCoordinations.clear();
904
+ this.activeAgents.clear();
905
+ this.emit('shutdown');
906
+ }
907
+ }
908
+ exports.QueenAgent = QueenAgent;
909
+ //# sourceMappingURL=queen-agent.js.map