snow-flow 1.3.4 → 1.3.5

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.
@@ -0,0 +1,401 @@
1
+ "use strict";
2
+ /**
3
+ * Hierarchical Memory System for Snow-Flow
4
+ * Extends base MemorySystem with ServiceNow-specific patterns
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.HierarchicalMemorySystem = void 0;
8
+ const memory_system_1 = require("./memory-system");
9
+ const logger_1 = require("../utils/logger");
10
+ class HierarchicalMemorySystem extends memory_system_1.MemorySystem {
11
+ constructor(options) {
12
+ super(options);
13
+ this.namespaceIndex = new Map();
14
+ this.typeIndex = new Map();
15
+ this.tagIndex = new Map();
16
+ this.logger = new logger_1.Logger('HierarchicalMemorySystem');
17
+ }
18
+ /**
19
+ * Initialize with enhanced tables for hierarchical storage
20
+ */
21
+ async initialize() {
22
+ await super.initialize();
23
+ await this.createHierarchicalTables();
24
+ await this.buildIndexes();
25
+ }
26
+ /**
27
+ * Create additional tables for hierarchical organization
28
+ */
29
+ async createHierarchicalTables() {
30
+ const tables = [
31
+ // Enhanced memory store with namespace and type
32
+ `CREATE TABLE IF NOT EXISTS hierarchical_memory (
33
+ key TEXT PRIMARY KEY,
34
+ namespace TEXT NOT NULL,
35
+ type TEXT NOT NULL,
36
+ value TEXT NOT NULL,
37
+ metadata TEXT,
38
+ ttl INTEGER,
39
+ created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
40
+ updated_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
41
+ expires_at INTEGER,
42
+ version INTEGER DEFAULT 1
43
+ )`,
44
+ // Tag associations
45
+ `CREATE TABLE IF NOT EXISTS memory_tags (
46
+ key TEXT NOT NULL,
47
+ tag TEXT NOT NULL,
48
+ PRIMARY KEY (key, tag),
49
+ FOREIGN KEY (key) REFERENCES hierarchical_memory(key) ON DELETE CASCADE
50
+ )`,
51
+ // Relationships between memory entries
52
+ `CREATE TABLE IF NOT EXISTS memory_relationships (
53
+ source_key TEXT NOT NULL,
54
+ target_key TEXT NOT NULL,
55
+ relationship_type TEXT NOT NULL,
56
+ metadata TEXT,
57
+ created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
58
+ PRIMARY KEY (source_key, target_key, relationship_type),
59
+ FOREIGN KEY (source_key) REFERENCES hierarchical_memory(key) ON DELETE CASCADE,
60
+ FOREIGN KEY (target_key) REFERENCES hierarchical_memory(key) ON DELETE CASCADE
61
+ )`,
62
+ // Agent memory associations
63
+ `CREATE TABLE IF NOT EXISTS agent_memory (
64
+ agent_id TEXT NOT NULL,
65
+ memory_key TEXT NOT NULL,
66
+ access_type TEXT NOT NULL, -- 'read', 'write', 'owner'
67
+ accessed_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
68
+ PRIMARY KEY (agent_id, memory_key),
69
+ FOREIGN KEY (memory_key) REFERENCES hierarchical_memory(key) ON DELETE CASCADE
70
+ )`,
71
+ // Memory access patterns for learning
72
+ `CREATE TABLE IF NOT EXISTS memory_access_patterns (
73
+ pattern_id TEXT PRIMARY KEY,
74
+ pattern_type TEXT NOT NULL,
75
+ frequency INTEGER DEFAULT 1,
76
+ last_accessed INTEGER DEFAULT (strftime('%s', 'now') * 1000),
77
+ metadata TEXT
78
+ )`,
79
+ ];
80
+ for (const table of tables) {
81
+ await this.execute(table);
82
+ }
83
+ // Create indexes for performance
84
+ const indexes = [
85
+ 'CREATE INDEX IF NOT EXISTS idx_namespace ON hierarchical_memory(namespace)',
86
+ 'CREATE INDEX IF NOT EXISTS idx_type ON hierarchical_memory(type)',
87
+ 'CREATE INDEX IF NOT EXISTS idx_expires ON hierarchical_memory(expires_at)',
88
+ 'CREATE INDEX IF NOT EXISTS idx_tags ON memory_tags(tag)',
89
+ 'CREATE INDEX IF NOT EXISTS idx_relationships ON memory_relationships(relationship_type)',
90
+ 'CREATE INDEX IF NOT EXISTS idx_agent_memory ON agent_memory(agent_id)',
91
+ ];
92
+ for (const index of indexes) {
93
+ await this.execute(index);
94
+ }
95
+ }
96
+ /**
97
+ * Store with hierarchical organization
98
+ */
99
+ async storeHierarchical(entry) {
100
+ if (!entry.key)
101
+ throw new Error('Key is required');
102
+ // Extract namespace and type from key pattern
103
+ const keyParts = entry.key.split('/');
104
+ const namespace = entry.namespace || keyParts[0] || 'default';
105
+ const type = entry.type || keyParts[1] || 'general';
106
+ const metadata = {
107
+ created: new Date().toISOString(),
108
+ updated: new Date().toISOString(),
109
+ version: 1,
110
+ tags: entry.metadata?.tags || [],
111
+ relationships: entry.metadata?.relationships || {},
112
+ dependencies: entry.metadata?.dependencies || {},
113
+ ...entry.metadata,
114
+ };
115
+ const ttl = entry.ttl || 86400000 * 7; // 7 days default
116
+ const expiresAt = Date.now() + ttl;
117
+ // Check if exists for versioning
118
+ const existing = await this.getHierarchical(entry.key);
119
+ if (existing) {
120
+ metadata.version = (existing.metadata?.version || 0) + 1;
121
+ metadata.created = existing.metadata?.created || metadata.created;
122
+ }
123
+ // Store in hierarchical table
124
+ await this.execute(`
125
+ INSERT OR REPLACE INTO hierarchical_memory
126
+ (key, namespace, type, value, metadata, ttl, expires_at, version, updated_at)
127
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
128
+ `, [
129
+ entry.key,
130
+ namespace,
131
+ type,
132
+ JSON.stringify(entry.value),
133
+ JSON.stringify(metadata),
134
+ ttl,
135
+ expiresAt,
136
+ metadata.version,
137
+ Date.now()
138
+ ]);
139
+ // Update tags
140
+ if (metadata.tags.length > 0) {
141
+ await this.updateTags(entry.key, metadata.tags);
142
+ }
143
+ // Update indexes
144
+ this.updateLocalIndexes(entry.key, namespace, type, metadata.tags);
145
+ // Store in base system for compatibility
146
+ await super.store(entry.key, entry.value, ttl);
147
+ this.emit('memory:hierarchical:stored', { key: entry.key, namespace, type });
148
+ }
149
+ /**
150
+ * Get with full hierarchical metadata
151
+ */
152
+ async getHierarchical(key) {
153
+ const result = await this.query(`
154
+ SELECT * FROM hierarchical_memory
155
+ WHERE key = ? AND expires_at > ?
156
+ `, [key, Date.now()]);
157
+ if (!result || result.length === 0)
158
+ return null;
159
+ const row = result[0];
160
+ const tags = await this.getTags(key);
161
+ return {
162
+ key: row.key,
163
+ namespace: row.namespace,
164
+ type: row.type,
165
+ value: JSON.parse(row.value),
166
+ metadata: {
167
+ ...JSON.parse(row.metadata || '{}'),
168
+ tags,
169
+ },
170
+ ttl: row.ttl,
171
+ };
172
+ }
173
+ /**
174
+ * Search with hierarchical patterns
175
+ */
176
+ async search(options) {
177
+ let sql = 'SELECT DISTINCT h.* FROM hierarchical_memory h';
178
+ const params = [];
179
+ const conditions = [];
180
+ // Join with tags if needed
181
+ if (options.tags && options.tags.length > 0) {
182
+ sql += ' INNER JOIN memory_tags t ON h.key = t.key';
183
+ conditions.push(`t.tag IN (${options.tags.map(() => '?').join(',')})`);
184
+ params.push(...options.tags);
185
+ }
186
+ // Add namespace filter
187
+ if (options.namespace) {
188
+ conditions.push('h.namespace = ?');
189
+ params.push(options.namespace);
190
+ }
191
+ // Add type filter
192
+ if (options.type) {
193
+ conditions.push('h.type = ?');
194
+ params.push(options.type);
195
+ }
196
+ // Add pattern matching
197
+ if (options.pattern) {
198
+ conditions.push('h.key LIKE ?');
199
+ params.push(`%${options.pattern}%`);
200
+ }
201
+ // Add expiration filter
202
+ if (!options.includeExpired) {
203
+ conditions.push('h.expires_at > ?');
204
+ params.push(Date.now());
205
+ }
206
+ // Combine conditions
207
+ if (conditions.length > 0) {
208
+ sql += ' WHERE ' + conditions.join(' AND ');
209
+ }
210
+ // Add ordering and limit
211
+ sql += ' ORDER BY h.updated_at DESC';
212
+ if (options.limit) {
213
+ sql += ' LIMIT ?';
214
+ params.push(options.limit);
215
+ }
216
+ const results = await this.query(sql, params);
217
+ // Fetch tags and format results
218
+ const entries = [];
219
+ for (const row of results) {
220
+ const tags = await this.getTags(row.key);
221
+ entries.push({
222
+ key: row.key,
223
+ namespace: row.namespace,
224
+ type: row.type,
225
+ value: JSON.parse(row.value),
226
+ metadata: {
227
+ ...JSON.parse(row.metadata || '{}'),
228
+ tags,
229
+ },
230
+ ttl: row.ttl,
231
+ });
232
+ }
233
+ return entries;
234
+ }
235
+ /**
236
+ * Create relationship between entries
237
+ */
238
+ async createRelationship(sourceKey, targetKey, relationshipType, metadata) {
239
+ await this.execute(`
240
+ INSERT OR REPLACE INTO memory_relationships
241
+ (source_key, target_key, relationship_type, metadata)
242
+ VALUES (?, ?, ?, ?)
243
+ `, [sourceKey, targetKey, relationshipType, JSON.stringify(metadata || {})]);
244
+ this.emit('memory:relationship:created', { sourceKey, targetKey, relationshipType });
245
+ }
246
+ /**
247
+ * Get related entries
248
+ */
249
+ async getRelated(key, relationshipType) {
250
+ let sql = `
251
+ SELECT DISTINCT h.*
252
+ FROM hierarchical_memory h
253
+ INNER JOIN memory_relationships r ON (h.key = r.target_key OR h.key = r.source_key)
254
+ WHERE (r.source_key = ? OR r.target_key = ?) AND h.key != ?
255
+ `;
256
+ const params = [key, key, key];
257
+ if (relationshipType) {
258
+ sql += ' AND r.relationship_type = ?';
259
+ params.push(relationshipType);
260
+ }
261
+ const results = await this.query(sql, params);
262
+ const entries = [];
263
+ for (const row of results) {
264
+ const entry = await this.getHierarchical(row.key);
265
+ if (entry)
266
+ entries.push(entry);
267
+ }
268
+ return entries;
269
+ }
270
+ /**
271
+ * Associate memory with agent
272
+ */
273
+ async associateWithAgent(agentId, memoryKey, accessType) {
274
+ await this.execute(`
275
+ INSERT OR REPLACE INTO agent_memory (agent_id, memory_key, access_type)
276
+ VALUES (?, ?, ?)
277
+ `, [agentId, memoryKey, accessType]);
278
+ }
279
+ /**
280
+ * Get agent's memory entries
281
+ */
282
+ async getAgentMemory(agentId, accessType) {
283
+ let sql = `
284
+ SELECT h.* FROM hierarchical_memory h
285
+ INNER JOIN agent_memory a ON h.key = a.memory_key
286
+ WHERE a.agent_id = ?
287
+ `;
288
+ const params = [agentId];
289
+ if (accessType) {
290
+ sql += ' AND a.access_type = ?';
291
+ params.push(accessType);
292
+ }
293
+ const results = await this.query(sql, params);
294
+ const entries = [];
295
+ for (const row of results) {
296
+ const entry = await this.getHierarchical(row.key);
297
+ if (entry)
298
+ entries.push(entry);
299
+ }
300
+ return entries;
301
+ }
302
+ /**
303
+ * Track access pattern for learning
304
+ */
305
+ async trackAccessPattern(patternType, metadata) {
306
+ const patternId = `${patternType}_${Date.now()}`;
307
+ await this.execute(`
308
+ INSERT INTO memory_access_patterns (pattern_id, pattern_type, metadata)
309
+ VALUES (?, ?, ?)
310
+ ON CONFLICT(pattern_id) DO UPDATE SET
311
+ frequency = frequency + 1,
312
+ last_accessed = strftime('%s', 'now') * 1000
313
+ `, [patternId, patternType, JSON.stringify(metadata || {})]);
314
+ }
315
+ /**
316
+ * Get namespace statistics
317
+ */
318
+ async getNamespaceStats() {
319
+ const results = await this.query(`
320
+ SELECT namespace, COUNT(*) as count
321
+ FROM hierarchical_memory
322
+ WHERE expires_at > ?
323
+ GROUP BY namespace
324
+ `, [Date.now()]);
325
+ const stats = {};
326
+ for (const row of results) {
327
+ stats[row.namespace] = row.count;
328
+ }
329
+ return stats;
330
+ }
331
+ /**
332
+ * Helper methods
333
+ */
334
+ async updateTags(key, tags) {
335
+ // Remove existing tags
336
+ await this.execute('DELETE FROM memory_tags WHERE key = ?', [key]);
337
+ // Insert new tags
338
+ for (const tag of tags) {
339
+ await this.execute('INSERT INTO memory_tags (key, tag) VALUES (?, ?)', [key, tag]);
340
+ }
341
+ }
342
+ async getTags(key) {
343
+ const results = await this.query('SELECT tag FROM memory_tags WHERE key = ?', [key]);
344
+ return results.map(r => r.tag);
345
+ }
346
+ updateLocalIndexes(key, namespace, type, tags) {
347
+ // Update namespace index
348
+ if (!this.namespaceIndex.has(namespace)) {
349
+ this.namespaceIndex.set(namespace, new Set());
350
+ }
351
+ this.namespaceIndex.get(namespace).add(key);
352
+ // Update type index
353
+ if (!this.typeIndex.has(type)) {
354
+ this.typeIndex.set(type, new Set());
355
+ }
356
+ this.typeIndex.get(type).add(key);
357
+ // Update tag index
358
+ for (const tag of tags) {
359
+ if (!this.tagIndex.has(tag)) {
360
+ this.tagIndex.set(tag, new Set());
361
+ }
362
+ this.tagIndex.get(tag).add(key);
363
+ }
364
+ }
365
+ async buildIndexes() {
366
+ // Build indexes from existing data
367
+ const results = await this.query(`
368
+ SELECT key, namespace, type FROM hierarchical_memory
369
+ WHERE expires_at > ?
370
+ `, [Date.now()]);
371
+ for (const row of results) {
372
+ const tags = await this.getTags(row.key);
373
+ this.updateLocalIndexes(row.key, row.namespace, row.type, tags);
374
+ }
375
+ }
376
+ /**
377
+ * Cleanup expired entries
378
+ */
379
+ async cleanupExpired() {
380
+ const result = await this.query(`
381
+ DELETE FROM hierarchical_memory
382
+ WHERE expires_at <= ?
383
+ RETURNING key
384
+ `, [Date.now()]);
385
+ // Update local indexes
386
+ for (const row of result) {
387
+ // Remove from indexes
388
+ for (const [namespace, keys] of this.namespaceIndex) {
389
+ keys.delete(row.key);
390
+ }
391
+ for (const [type, keys] of this.typeIndex) {
392
+ keys.delete(row.key);
393
+ }
394
+ for (const [tag, keys] of this.tagIndex) {
395
+ keys.delete(row.key);
396
+ }
397
+ }
398
+ return result.length;
399
+ }
400
+ }
401
+ exports.HierarchicalMemorySystem = HierarchicalMemorySystem;
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ /**
3
+ * Snow-Flow Memory Patterns
4
+ * Hierarchical memory organization for ServiceNow development
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.SnowFlowWorkflowExamples = exports.SNOW_FLOW_AGENT_CAPABILITIES = exports.SnowFlowMemoryOrganizer = void 0;
8
+ class SnowFlowMemoryOrganizer {
9
+ /**
10
+ * Generate hierarchical key for ServiceNow artifacts
11
+ */
12
+ static generateKey(category, type, name) {
13
+ const sanitizedName = name.toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, '');
14
+ return `${category}/${type}/${sanitizedName}`;
15
+ }
16
+ /**
17
+ * Store widget information with metadata
18
+ */
19
+ static getWidgetMemoryStructure(widgetName) {
20
+ return {
21
+ key: this.generateKey('artifacts', 'widgets', widgetName),
22
+ metadata: {
23
+ type: 'service_portal_widget',
24
+ created: new Date().toISOString(),
25
+ tags: ['widget', 'ui', 'service-portal'],
26
+ },
27
+ searchableFields: ['name', 'title', 'description', 'template', 'script'],
28
+ };
29
+ }
30
+ /**
31
+ * Store flow information with relationships
32
+ */
33
+ static getFlowMemoryStructure(flowName) {
34
+ return {
35
+ key: this.generateKey('artifacts', 'flows', flowName),
36
+ metadata: {
37
+ type: 'flow_designer',
38
+ created: new Date().toISOString(),
39
+ tags: ['flow', 'automation', 'workflow'],
40
+ },
41
+ relationships: {
42
+ triggers: [],
43
+ actions: [],
44
+ subflows: [],
45
+ tables: [],
46
+ },
47
+ };
48
+ }
49
+ /**
50
+ * Store script information with dependencies
51
+ */
52
+ static getScriptMemoryStructure(scriptName, scriptType) {
53
+ return {
54
+ key: this.generateKey('code', `${scriptType}-scripts`, scriptName),
55
+ metadata: {
56
+ type: scriptType,
57
+ created: new Date().toISOString(),
58
+ tags: ['script', scriptType],
59
+ },
60
+ dependencies: {
61
+ tables: [],
62
+ scriptIncludes: [],
63
+ glideRecords: [],
64
+ apis: [],
65
+ },
66
+ };
67
+ }
68
+ /**
69
+ * Store test results with coverage
70
+ */
71
+ static getTestMemoryStructure(testName, testType) {
72
+ return {
73
+ key: this.generateKey('tests', testType, testName),
74
+ metadata: {
75
+ type: `${testType}_test`,
76
+ executed: new Date().toISOString(),
77
+ tags: ['test', testType],
78
+ },
79
+ results: {
80
+ passed: 0,
81
+ failed: 0,
82
+ skipped: 0,
83
+ coverage: 0,
84
+ duration: 0,
85
+ },
86
+ };
87
+ }
88
+ /**
89
+ * Store deployment information
90
+ */
91
+ static getDeploymentMemoryStructure(updateSetName) {
92
+ return {
93
+ key: this.generateKey('deploy', 'update-sets', updateSetName),
94
+ metadata: {
95
+ type: 'update_set',
96
+ created: new Date().toISOString(),
97
+ tags: ['deployment', 'update-set'],
98
+ },
99
+ contents: {
100
+ artifacts: [],
101
+ dependencies: [],
102
+ conflicts: [],
103
+ targetInstance: '',
104
+ },
105
+ };
106
+ }
107
+ }
108
+ exports.SnowFlowMemoryOrganizer = SnowFlowMemoryOrganizer;
109
+ /**
110
+ * Agent capability mappings for ServiceNow development
111
+ */
112
+ exports.SNOW_FLOW_AGENT_CAPABILITIES = {
113
+ // UI Development
114
+ 'widget-developer': ['html', 'css', 'javascript', 'angular', 'service-portal-api'],
115
+ 'ui-designer': ['ui-builder', 'themes', 'branding', 'responsive-design'],
116
+ // Flow Development
117
+ 'flow-builder': ['flow-designer', 'triggers', 'actions', 'subflows', 'approvals'],
118
+ 'integration-specialist': ['rest-api', 'soap', 'mid-server', 'integration-hub'],
119
+ // Scripting
120
+ 'script-developer': ['glide-api', 'business-rules', 'script-includes', 'scheduled-jobs'],
121
+ 'client-scripter': ['client-scripts', 'ui-policies', 'catalog-client-scripts'],
122
+ // Data & Configuration
123
+ 'data-architect': ['tables', 'relationships', 'acls', 'data-policies'],
124
+ 'security-engineer': ['security-rules', 'authentication', 'encryption', 'audit'],
125
+ // Testing & Quality
126
+ 'test-engineer': ['atf', 'unit-testing', 'regression-testing', 'performance-testing'],
127
+ 'quality-analyst': ['code-review', 'best-practices', 'performance-optimization'],
128
+ // Documentation & Training
129
+ 'technical-writer': ['api-docs', 'user-guides', 'runbooks', 'knowledge-articles'],
130
+ 'solution-architect': ['architecture-docs', 'design-patterns', 'roadmaps'],
131
+ };
132
+ /**
133
+ * Example usage patterns for ServiceNow development
134
+ */
135
+ class SnowFlowWorkflowExamples {
136
+ /**
137
+ * Example: Create incident dashboard widget
138
+ */
139
+ static async createIncidentDashboard() {
140
+ // 1. Store requirements
141
+ await memory.store('specs/requirements/incident-dashboard', {
142
+ title: 'Incident Dashboard Widget',
143
+ features: ['real-time updates', 'priority filtering', 'assignment groups'],
144
+ acceptance: ['shows active incidents', 'updates every 30s', 'filterable'],
145
+ });
146
+ // 2. Spawn specialized agents
147
+ const agents = await Promise.all([
148
+ agentSpawn({ type: 'widget-developer', capabilities: exports.SNOW_FLOW_AGENT_CAPABILITIES['widget-developer'] }),
149
+ agentSpawn({ type: 'ui-designer', capabilities: exports.SNOW_FLOW_AGENT_CAPABILITIES['ui-designer'] }),
150
+ agentSpawn({ type: 'test-engineer', capabilities: exports.SNOW_FLOW_AGENT_CAPABILITIES['test-engineer'] }),
151
+ ]);
152
+ // 3. Coordinate work
153
+ await agentCommunicate({
154
+ to: agents[0].id,
155
+ message: 'Create widget structure based on specs/requirements/incident-dashboard'
156
+ });
157
+ await agentCommunicate({
158
+ to: agents[1].id,
159
+ message: 'Design responsive layout for incident data visualization'
160
+ });
161
+ // 4. Store artifacts
162
+ await memory.store('artifacts/widgets/incident-dashboard', {
163
+ html: '<!-- widget template -->',
164
+ css: '/* widget styles */',
165
+ clientScript: '// client controller',
166
+ serverScript: '// server script',
167
+ });
168
+ // 5. Track progress
169
+ await taskUpdate({ taskId: 'incident-dashboard', progress: 100 });
170
+ }
171
+ /**
172
+ * Example: Create approval workflow
173
+ */
174
+ static async createApprovalFlow() {
175
+ // 1. Store flow design
176
+ await memory.store('architecture/decisions/approval-flow', {
177
+ pattern: 'multi-level-approval',
178
+ levels: ['manager', 'director', 'vp'],
179
+ escalation: 'time-based',
180
+ });
181
+ // 2. Spawn flow specialists
182
+ const flowBuilder = await agentSpawn({
183
+ type: 'flow-builder',
184
+ capabilities: exports.SNOW_FLOW_AGENT_CAPABILITIES['flow-builder']
185
+ });
186
+ // 3. Build flow with memory reference
187
+ await agentCommunicate({
188
+ to: flowBuilder.id,
189
+ message: 'Build approval flow using architecture/decisions/approval-flow pattern'
190
+ });
191
+ // 4. Store flow artifact
192
+ await memory.store('artifacts/flows/equipment-approval', {
193
+ trigger: 'record.inserted',
194
+ actions: ['lookup-manager', 'send-approval', 'wait-response', 'update-record'],
195
+ table: 'x_company_equipment',
196
+ });
197
+ }
198
+ }
199
+ exports.SnowFlowWorkflowExamples = SnowFlowWorkflowExamples;
@@ -0,0 +1,313 @@
1
+ "use strict";
2
+ /**
3
+ * Queen Memory System with Hierarchical Patterns
4
+ * Enhanced memory system for ServiceNow Queen Agent coordination
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.QueenMemorySystem = void 0;
8
+ const snow_flow_memory_patterns_1 = require("../memory/snow-flow-memory-patterns");
9
+ const logger_1 = require("../utils/logger");
10
+ const events_1 = require("events");
11
+ class QueenMemorySystem extends events_1.EventEmitter {
12
+ constructor(memory) {
13
+ super();
14
+ this.objectiveCache = new Map();
15
+ this.agentIndex = new Map(); // agentId -> memory keys
16
+ this.memory = memory;
17
+ this.logger = new logger_1.Logger('QueenMemorySystem');
18
+ }
19
+ /**
20
+ * Store objective with full context
21
+ */
22
+ async storeObjective(objectiveId, objective) {
23
+ const key = `objectives/${objectiveId}/definition`;
24
+ await this.memory.storeHierarchical({
25
+ key,
26
+ namespace: 'objectives',
27
+ type: 'definition',
28
+ value: objective,
29
+ metadata: {
30
+ tags: ['objective', 'requirement', objective.priority || 'medium'],
31
+ created: new Date().toISOString(),
32
+ },
33
+ ttl: 86400000 * 30, // 30 days
34
+ });
35
+ this.objectiveCache.set(objectiveId, objective);
36
+ this.emit('objective:stored', { objectiveId, objective });
37
+ }
38
+ /**
39
+ * Store task analysis with patterns
40
+ */
41
+ async storeTaskAnalysis(objectiveId, analysis) {
42
+ const key = `objectives/${objectiveId}/analysis`;
43
+ await this.memory.storeHierarchical({
44
+ key,
45
+ namespace: 'objectives',
46
+ type: 'analysis',
47
+ value: analysis,
48
+ metadata: {
49
+ tags: ['analysis', analysis.taskType, 'complexity-' + analysis.estimatedComplexity],
50
+ relationships: {
51
+ requires: analysis.dependencies || [],
52
+ similar: analysis.similarPatterns || [],
53
+ },
54
+ },
55
+ });
56
+ // Track patterns for learning
57
+ if (analysis.similarPatterns && analysis.similarPatterns.length > 0) {
58
+ await this.memory.trackAccessPattern('pattern_reuse', {
59
+ objectiveId,
60
+ patterns: analysis.similarPatterns,
61
+ });
62
+ }
63
+ }
64
+ /**
65
+ * Store agent profile with capabilities
66
+ */
67
+ async storeAgentProfile(agentId, profile) {
68
+ const key = `agents/${agentId}/profile`;
69
+ await this.memory.storeHierarchical({
70
+ key,
71
+ namespace: 'agents',
72
+ type: 'profile',
73
+ value: profile,
74
+ metadata: {
75
+ tags: ['agent', profile.type, profile.status, ...profile.capabilities],
76
+ },
77
+ });
78
+ // Update agent index
79
+ if (!this.agentIndex.has(agentId)) {
80
+ this.agentIndex.set(agentId, new Set());
81
+ }
82
+ this.agentIndex.get(agentId).add(key);
83
+ }
84
+ /**
85
+ * Store agent task assignment
86
+ */
87
+ async storeAgentTask(agentId, taskId, task) {
88
+ const key = `agents/${agentId}/tasks/${taskId}`;
89
+ await this.memory.storeHierarchical({
90
+ key,
91
+ namespace: 'agents',
92
+ type: 'task',
93
+ value: task,
94
+ metadata: {
95
+ tags: ['task', 'agent-task', `priority-${task.priority}`],
96
+ relationships: {
97
+ assignedTo: [agentId],
98
+ dependsOn: task.dependencies || [],
99
+ },
100
+ },
101
+ });
102
+ // Create relationship
103
+ await this.memory.createRelationship(`agents/${agentId}/profile`, key, 'assigned_task', { assignedAt: new Date().toISOString() });
104
+ this.agentIndex.get(agentId)?.add(key);
105
+ }
106
+ /**
107
+ * Store ServiceNow artifact with full metadata
108
+ */
109
+ async storeArtifact(artifact) {
110
+ const key = `artifacts/${artifact.type}s/${artifact.name}`;
111
+ const memoryStructure = this.getArtifactMemoryStructure(artifact);
112
+ await this.memory.storeHierarchical({
113
+ key,
114
+ namespace: 'artifacts',
115
+ type: artifact.type,
116
+ value: {
117
+ ...artifact,
118
+ memoryMetadata: memoryStructure,
119
+ },
120
+ metadata: {
121
+ tags: ['artifact', artifact.type, 'servicenow'],
122
+ relationships: {
123
+ dependsOn: artifact.dependencies || [],
124
+ deployedTo: artifact.deployment ? [artifact.deployment.instance] : [],
125
+ },
126
+ },
127
+ });
128
+ // Store deployment info separately if exists
129
+ if (artifact.deployment) {
130
+ await this.storeDeployment(artifact.name, artifact.deployment);
131
+ }
132
+ }
133
+ /**
134
+ * Store deployment information
135
+ */
136
+ async storeDeployment(artifactName, deployment) {
137
+ const deploymentId = `${artifactName}_${deployment.instance}_${Date.now()}`;
138
+ const key = `artifacts/deployments/${deploymentId}`;
139
+ await this.memory.storeHierarchical({
140
+ key,
141
+ namespace: 'artifacts',
142
+ type: 'deployment',
143
+ value: deployment,
144
+ metadata: {
145
+ tags: ['deployment', deployment.status, deployment.instance],
146
+ },
147
+ });
148
+ }
149
+ /**
150
+ * Store successful pattern for learning
151
+ */
152
+ async storeSuccessfulPattern(pattern) {
153
+ const key = `patterns/successful/${pattern.type}/${Date.now()}`;
154
+ await this.memory.storeHierarchical({
155
+ key,
156
+ namespace: 'patterns',
157
+ type: 'successful',
158
+ value: pattern,
159
+ metadata: {
160
+ tags: ['pattern', 'success', pattern.type],
161
+ },
162
+ ttl: 86400000 * 90, // 90 days
163
+ });
164
+ this.emit('pattern:learned', { type: 'success', pattern });
165
+ }
166
+ /**
167
+ * Store failure pattern for avoidance
168
+ */
169
+ async storeFailurePattern(pattern) {
170
+ const key = `patterns/failures/${pattern.type}/${Date.now()}`;
171
+ await this.memory.storeHierarchical({
172
+ key,
173
+ namespace: 'patterns',
174
+ type: 'failure',
175
+ value: pattern,
176
+ metadata: {
177
+ tags: ['pattern', 'failure', pattern.type],
178
+ },
179
+ ttl: 86400000 * 90, // 90 days
180
+ });
181
+ this.emit('pattern:learned', { type: 'failure', pattern });
182
+ }
183
+ /**
184
+ * Find similar objectives from history
185
+ */
186
+ async findSimilarObjectives(objective, limit = 5) {
187
+ // Search by objective keywords
188
+ const keywords = objective.toLowerCase().split(' ')
189
+ .filter(word => word.length > 3);
190
+ const results = await this.memory.search({
191
+ namespace: 'objectives',
192
+ type: 'definition',
193
+ limit: limit * 2, // Get more to filter
194
+ });
195
+ // Score by keyword matches
196
+ const scored = results.map(entry => {
197
+ const desc = (entry.value.description || '').toLowerCase();
198
+ const score = keywords.reduce((sum, keyword) => sum + (desc.includes(keyword) ? 1 : 0), 0);
199
+ return { entry, score };
200
+ });
201
+ // Return top matches
202
+ return scored
203
+ .filter(item => item.score > 0)
204
+ .sort((a, b) => b.score - a.score)
205
+ .slice(0, limit)
206
+ .map(item => item.entry);
207
+ }
208
+ /**
209
+ * Get successful patterns for a task type
210
+ */
211
+ async getSuccessfulPatterns(taskType) {
212
+ return await this.memory.search({
213
+ namespace: 'patterns',
214
+ type: 'successful',
215
+ tags: [taskType],
216
+ limit: 10,
217
+ });
218
+ }
219
+ /**
220
+ * Get agent's complete memory
221
+ */
222
+ async getAgentMemory(agentId) {
223
+ return await this.memory.getAgentMemory(agentId);
224
+ }
225
+ /**
226
+ * Get swarm coordination data
227
+ */
228
+ async getSwarmData(swarmId) {
229
+ const [topology, communication, consensus] = await Promise.all([
230
+ this.memory.getHierarchical(`swarm/${swarmId}/topology`),
231
+ this.memory.search({
232
+ namespace: 'swarm',
233
+ pattern: `${swarmId}/communication`,
234
+ }),
235
+ this.memory.search({
236
+ namespace: 'swarm',
237
+ pattern: `${swarmId}/consensus`,
238
+ }),
239
+ ]);
240
+ return {
241
+ topology: topology?.value || null,
242
+ communication: communication.map(c => c.value),
243
+ consensus: consensus.map(c => c.value),
244
+ };
245
+ }
246
+ /**
247
+ * Store inter-agent communication
248
+ */
249
+ async storeAgentCommunication(fromAgent, toAgent, message, swarmId) {
250
+ const key = swarmId
251
+ ? `swarm/${swarmId}/communication/${Date.now()}`
252
+ : `agents/communication/${fromAgent}_to_${toAgent}_${Date.now()}`;
253
+ await this.memory.storeHierarchical({
254
+ key,
255
+ namespace: swarmId ? 'swarm' : 'agents',
256
+ type: 'communication',
257
+ value: {
258
+ from: fromAgent,
259
+ to: toAgent,
260
+ message,
261
+ timestamp: new Date().toISOString(),
262
+ },
263
+ metadata: {
264
+ tags: ['communication', 'agent-message'],
265
+ relationships: {
266
+ from: [fromAgent],
267
+ to: [toAgent],
268
+ },
269
+ },
270
+ });
271
+ }
272
+ /**
273
+ * Get namespace statistics for monitoring
274
+ */
275
+ async getMemoryStats() {
276
+ const namespaces = await this.memory.getNamespaceStats();
277
+ return {
278
+ namespaces,
279
+ totalEntries: Object.values(namespaces).reduce((sum, count) => sum + count, 0),
280
+ patterns: namespaces['patterns'] || 0,
281
+ artifacts: namespaces['artifacts'] || 0,
282
+ agents: namespaces['agents'] || 0,
283
+ };
284
+ }
285
+ /**
286
+ * Helper to get artifact memory structure
287
+ */
288
+ getArtifactMemoryStructure(artifact) {
289
+ switch (artifact.type) {
290
+ case 'widget':
291
+ return snow_flow_memory_patterns_1.SnowFlowMemoryOrganizer.getWidgetMemoryStructure(artifact.name);
292
+ case 'flow':
293
+ return snow_flow_memory_patterns_1.SnowFlowMemoryOrganizer.getFlowMemoryStructure(artifact.name);
294
+ case 'script':
295
+ return snow_flow_memory_patterns_1.SnowFlowMemoryOrganizer.getScriptMemoryStructure(artifact.name, artifact.scriptType || 'server');
296
+ default:
297
+ return {
298
+ key: snow_flow_memory_patterns_1.SnowFlowMemoryOrganizer.generateKey('artifacts', artifact.type, artifact.name),
299
+ metadata: {
300
+ type: artifact.type,
301
+ created: new Date().toISOString(),
302
+ },
303
+ };
304
+ }
305
+ }
306
+ /**
307
+ * Clean up expired entries
308
+ */
309
+ async cleanup() {
310
+ return await this.memory.cleanupExpired();
311
+ }
312
+ }
313
+ exports.QueenMemorySystem = QueenMemorySystem;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "snow-flow",
3
- "version": "1.3.4",
3
+ "version": "1.3.5",
4
4
  "description": "ServiceNow Queen Agent - Hive-Mind Intelligence for ServiceNow Development inspired by claude-flow. Transform complex workflows into elegant one-command orchestration.",
5
5
  "main": "dist/index.js",
6
6
  "type": "commonjs",