snow-flow 2.0.3 → 2.0.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,378 @@
1
+ "use strict";
2
+ /**
3
+ * Snow-Flow Swarm Memory System
4
+ * Core SQLite database management for agent coordination
5
+ *
6
+ * This module provides the foundation for cross-agent communication,
7
+ * artifact tracking, and performance monitoring.
8
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || (function () {
26
+ var ownKeys = function(o) {
27
+ ownKeys = Object.getOwnPropertyNames || function (o) {
28
+ var ar = [];
29
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
30
+ return ar;
31
+ };
32
+ return ownKeys(o);
33
+ };
34
+ return function (mod) {
35
+ if (mod && mod.__esModule) return mod;
36
+ var result = {};
37
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
38
+ __setModuleDefault(result, mod);
39
+ return result;
40
+ };
41
+ })();
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.SwarmMemory = void 0;
44
+ const logger_js_1 = require("../utils/logger.js");
45
+ const path = __importStar(require("path"));
46
+ const fs = __importStar(require("fs"));
47
+ let Database;
48
+ try {
49
+ Database = require('better-sqlite3');
50
+ }
51
+ catch (error) {
52
+ console.error('Failed to load better-sqlite3:', error);
53
+ throw new Error('better-sqlite3 module is required. Please run: npm install better-sqlite3');
54
+ }
55
+ class SwarmMemory {
56
+ constructor(config = {}) {
57
+ this.migrationVersion = 1;
58
+ this.logger = new logger_js_1.Logger('SwarmMemory');
59
+ this.config = config;
60
+ // Ensure memory directory exists
61
+ if (!config.inMemory && !config.dbPath) {
62
+ const memoryDir = path.join(process.cwd(), '.snow-flow', 'memory');
63
+ if (!fs.existsSync(memoryDir)) {
64
+ fs.mkdirSync(memoryDir, { recursive: true });
65
+ }
66
+ config.dbPath = path.join(memoryDir, 'swarm-memory.db');
67
+ }
68
+ // Initialize database
69
+ if (config.inMemory) {
70
+ this.db = new Database(':memory:');
71
+ this.logger.info('Initialized in-memory database');
72
+ }
73
+ else {
74
+ this.db = new Database(config.dbPath);
75
+ this.logger.info('Initialized file-based database', { path: config.dbPath });
76
+ }
77
+ // Configure database for performance
78
+ this.configureDatabase();
79
+ // Run migrations
80
+ if (config.autoMigrate !== false) {
81
+ this.migrate();
82
+ }
83
+ }
84
+ configureDatabase() {
85
+ // Enable foreign keys for data integrity
86
+ this.db.pragma('foreign_keys = ON');
87
+ // Optimize for concurrent reads
88
+ this.db.pragma('journal_mode = WAL');
89
+ // Increase cache size for better performance
90
+ this.db.pragma('cache_size = 10000');
91
+ // Optimize for fast queries
92
+ this.db.pragma('synchronous = NORMAL');
93
+ if (this.config.verbose) {
94
+ this.logger.info('Database configured for optimal performance');
95
+ }
96
+ }
97
+ migrate() {
98
+ this.logger.info('Running database migrations');
99
+ // Check current migration version
100
+ const userVersion = this.db.pragma('user_version', { simple: true });
101
+ if (userVersion < this.migrationVersion) {
102
+ this.logger.info(`Migrating from version ${userVersion} to ${this.migrationVersion}`);
103
+ try {
104
+ this.db.transaction(() => {
105
+ // Create all tables as specified in MCP_ARCHITECTURE.md
106
+ this.createTables();
107
+ // Create indexes for performance
108
+ this.createIndexes();
109
+ // Update migration version
110
+ this.db.pragma(`user_version = ${this.migrationVersion}`);
111
+ })();
112
+ this.logger.info('Migration completed successfully');
113
+ }
114
+ catch (error) {
115
+ this.logger.error('Migration failed', error);
116
+ throw new Error(`Database migration failed: ${error.message}`);
117
+ }
118
+ }
119
+ }
120
+ createTables() {
121
+ // Agent coordination and communication
122
+ this.db.exec(`
123
+ CREATE TABLE IF NOT EXISTS agent_coordination (
124
+ session_id TEXT NOT NULL,
125
+ agent_id TEXT NOT NULL,
126
+ agent_type TEXT NOT NULL,
127
+ status TEXT NOT NULL CHECK (status IN ('spawned', 'active', 'blocked', 'completed', 'failed')),
128
+ assigned_tasks TEXT NOT NULL,
129
+ progress_percentage INTEGER DEFAULT 0 CHECK (progress_percentage >= 0 AND progress_percentage <= 100),
130
+ last_activity TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
131
+ current_tool TEXT,
132
+ error_state TEXT,
133
+ PRIMARY KEY (session_id, agent_id)
134
+ );
135
+ `);
136
+ // ServiceNow artifact tracking
137
+ this.db.exec(`
138
+ CREATE TABLE IF NOT EXISTS servicenow_artifacts (
139
+ sys_id TEXT PRIMARY KEY,
140
+ artifact_type TEXT NOT NULL CHECK (artifact_type IN ('widget', 'flow', 'script', 'business_rule', 'table', 'catalog_item')),
141
+ name TEXT NOT NULL,
142
+ description TEXT,
143
+ created_by_agent TEXT NOT NULL,
144
+ session_id TEXT NOT NULL,
145
+ deployment_status TEXT NOT NULL CHECK (deployment_status IN ('created', 'tested', 'deployed', 'verified', 'failed')),
146
+ update_set_id TEXT,
147
+ dependencies TEXT, -- JSON array of dependent artifacts
148
+ metadata TEXT, -- JSON blob of artifact-specific data
149
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
150
+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
151
+ );
152
+ `);
153
+ // Inter-agent communication
154
+ this.db.exec(`
155
+ CREATE TABLE IF NOT EXISTS agent_messages (
156
+ id TEXT PRIMARY KEY,
157
+ session_id TEXT NOT NULL,
158
+ from_agent TEXT NOT NULL,
159
+ to_agent TEXT NOT NULL,
160
+ message_type TEXT NOT NULL CHECK (message_type IN ('handoff', 'dependency_ready', 'error', 'status_update', 'coordination')),
161
+ content TEXT NOT NULL,
162
+ artifact_reference TEXT,
163
+ timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
164
+ processed BOOLEAN DEFAULT FALSE
165
+ );
166
+ `);
167
+ // Shared context between agents
168
+ this.db.exec(`
169
+ CREATE TABLE IF NOT EXISTS shared_context (
170
+ session_id TEXT NOT NULL,
171
+ context_key TEXT NOT NULL,
172
+ context_value TEXT NOT NULL,
173
+ created_by_agent TEXT NOT NULL,
174
+ expires_at TIMESTAMP,
175
+ access_permissions TEXT, -- JSON array of agent types that can access
176
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
177
+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
178
+ PRIMARY KEY (session_id, context_key)
179
+ );
180
+ `);
181
+ // Deployment tracking
182
+ this.db.exec(`
183
+ CREATE TABLE IF NOT EXISTS deployment_history (
184
+ id TEXT PRIMARY KEY,
185
+ session_id TEXT NOT NULL,
186
+ artifact_sys_id TEXT NOT NULL,
187
+ deployment_type TEXT NOT NULL CHECK (deployment_type IN ('create', 'update', 'test', 'verify', 'rollback')),
188
+ success BOOLEAN NOT NULL,
189
+ deployment_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
190
+ agent_id TEXT NOT NULL,
191
+ error_details TEXT,
192
+ rollback_available BOOLEAN DEFAULT FALSE
193
+ );
194
+ `);
195
+ // Agent dependencies and handoffs
196
+ this.db.exec(`
197
+ CREATE TABLE IF NOT EXISTS agent_dependencies (
198
+ session_id TEXT NOT NULL,
199
+ agent_id TEXT NOT NULL,
200
+ depends_on_agent TEXT NOT NULL,
201
+ dependency_type TEXT NOT NULL CHECK (dependency_type IN ('artifact_ready', 'approval_needed', 'data_available', 'task_complete')),
202
+ artifact_reference TEXT,
203
+ status TEXT NOT NULL CHECK (status IN ('pending', 'satisfied', 'blocked', 'failed')),
204
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
205
+ satisfied_at TIMESTAMP,
206
+ PRIMARY KEY (session_id, agent_id, depends_on_agent)
207
+ );
208
+ `);
209
+ // Performance metrics
210
+ this.db.exec(`
211
+ CREATE TABLE IF NOT EXISTS performance_metrics (
212
+ id TEXT PRIMARY KEY,
213
+ session_id TEXT NOT NULL,
214
+ agent_id TEXT NOT NULL,
215
+ operation_name TEXT NOT NULL,
216
+ duration_ms INTEGER NOT NULL CHECK (duration_ms >= 0),
217
+ success BOOLEAN NOT NULL,
218
+ error_message TEXT,
219
+ timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
220
+ metadata TEXT -- JSON blob for additional metrics
221
+ );
222
+ `);
223
+ }
224
+ createIndexes() {
225
+ // Indexes for agent_coordination
226
+ this.db.exec(`
227
+ CREATE INDEX IF NOT EXISTS idx_agent_coordination_status
228
+ ON agent_coordination(status);
229
+
230
+ CREATE INDEX IF NOT EXISTS idx_agent_coordination_session
231
+ ON agent_coordination(session_id);
232
+ `);
233
+ // Indexes for servicenow_artifacts
234
+ this.db.exec(`
235
+ CREATE INDEX IF NOT EXISTS idx_artifacts_session
236
+ ON servicenow_artifacts(session_id);
237
+
238
+ CREATE INDEX IF NOT EXISTS idx_artifacts_type
239
+ ON servicenow_artifacts(artifact_type);
240
+
241
+ CREATE INDEX IF NOT EXISTS idx_artifacts_status
242
+ ON servicenow_artifacts(deployment_status);
243
+ `);
244
+ // Indexes for agent_messages
245
+ this.db.exec(`
246
+ CREATE INDEX IF NOT EXISTS idx_messages_session
247
+ ON agent_messages(session_id);
248
+
249
+ CREATE INDEX IF NOT EXISTS idx_messages_to_agent
250
+ ON agent_messages(to_agent, processed);
251
+
252
+ CREATE INDEX IF NOT EXISTS idx_messages_timestamp
253
+ ON agent_messages(timestamp);
254
+ `);
255
+ // Indexes for shared_context
256
+ this.db.exec(`
257
+ CREATE INDEX IF NOT EXISTS idx_context_session
258
+ ON shared_context(session_id);
259
+
260
+ CREATE INDEX IF NOT EXISTS idx_context_expires
261
+ ON shared_context(expires_at);
262
+ `);
263
+ // Indexes for performance_metrics
264
+ this.db.exec(`
265
+ CREATE INDEX IF NOT EXISTS idx_metrics_session
266
+ ON performance_metrics(session_id);
267
+
268
+ CREATE INDEX IF NOT EXISTS idx_metrics_agent
269
+ ON performance_metrics(agent_id);
270
+
271
+ CREATE INDEX IF NOT EXISTS idx_metrics_timestamp
272
+ ON performance_metrics(timestamp);
273
+ `);
274
+ }
275
+ /**
276
+ * Get the underlying database instance for direct queries
277
+ */
278
+ getDatabase() {
279
+ return this.db;
280
+ }
281
+ /**
282
+ * Prepare a statement for repeated execution
283
+ */
284
+ prepare(sql) {
285
+ return this.db.prepare(sql);
286
+ }
287
+ /**
288
+ * Execute a query and return all results
289
+ */
290
+ all(sql, params) {
291
+ const stmt = this.db.prepare(sql);
292
+ return params ? stmt.all(...params) : stmt.all();
293
+ }
294
+ /**
295
+ * Execute a query and return the first result
296
+ */
297
+ get(sql, params) {
298
+ const stmt = this.db.prepare(sql);
299
+ return params ? stmt.get(...params) : stmt.get();
300
+ }
301
+ /**
302
+ * Execute a statement that doesn't return data
303
+ */
304
+ run(sql, params) {
305
+ const stmt = this.db.prepare(sql);
306
+ return params ? stmt.run(...params) : stmt.run();
307
+ }
308
+ /**
309
+ * Execute multiple statements in a transaction
310
+ */
311
+ transaction(fn) {
312
+ const transaction = this.db.transaction(fn);
313
+ return transaction();
314
+ }
315
+ /**
316
+ * Clean up expired data
317
+ */
318
+ cleanup() {
319
+ this.logger.info('Running memory cleanup');
320
+ this.transaction(() => {
321
+ // Remove expired context
322
+ this.run(`
323
+ DELETE FROM shared_context
324
+ WHERE expires_at IS NOT NULL AND expires_at < datetime('now')
325
+ `);
326
+ // Archive old messages
327
+ const thirtyDaysAgo = new Date();
328
+ thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
329
+ this.run(`
330
+ DELETE FROM agent_messages
331
+ WHERE processed = 1 AND timestamp < ?
332
+ `, [thirtyDaysAgo.toISOString()]);
333
+ // Archive old performance metrics
334
+ this.run(`
335
+ DELETE FROM performance_metrics
336
+ WHERE timestamp < ?
337
+ `, [thirtyDaysAgo.toISOString()]);
338
+ });
339
+ // Optimize database
340
+ this.db.pragma('optimize');
341
+ this.logger.info('Memory cleanup completed');
342
+ }
343
+ /**
344
+ * Get database statistics
345
+ */
346
+ getStats() {
347
+ const stats = {};
348
+ const tables = [
349
+ 'agent_coordination',
350
+ 'servicenow_artifacts',
351
+ 'agent_messages',
352
+ 'shared_context',
353
+ 'deployment_history',
354
+ 'agent_dependencies',
355
+ 'performance_metrics'
356
+ ];
357
+ for (const table of tables) {
358
+ const count = this.get(`SELECT COUNT(*) as count FROM ${table}`)?.count || 0;
359
+ stats[table] = count;
360
+ }
361
+ // Add database size
362
+ const pageCount = this.db.pragma('page_count', { simple: true });
363
+ const pageSize = this.db.pragma('page_size', { simple: true });
364
+ if (pageCount && pageSize) {
365
+ stats.database_size_bytes = pageCount * pageSize;
366
+ }
367
+ return stats;
368
+ }
369
+ /**
370
+ * Close the database connection
371
+ */
372
+ close() {
373
+ this.logger.info('Closing database connection');
374
+ this.db.close();
375
+ }
376
+ }
377
+ exports.SwarmMemory = SwarmMemory;
378
+ //# sourceMappingURL=swarm-memory.js.map
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "snow-flow",
3
- "version": "2.0.3",
3
+ "version": "2.0.5",
4
4
  "description": "Snow-Flow: ServiceNow Advanced Intelligence Platform - 100+ real MCP tools with AI-powered swarm orchestration. Zero Mock Data, 100% Real API Integration. Natural language interface for ServiceNow operations.",
5
5
  "main": "dist/index.js",
6
6
  "type": "commonjs",
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const os = require('os');
6
+
7
+ console.log('šŸš€ Setting up Snow-Flow...');
8
+
9
+ // Check if we're in a global install
10
+ const isGlobalInstall = process.env.npm_config_global === 'true' ||
11
+ process.env.npm_config_global === true;
12
+
13
+ if (isGlobalInstall) {
14
+ console.log('āœ… Snow-Flow installed globally');
15
+ console.log('šŸ“ Run "snow-flow init" in your project directory to initialize');
16
+
17
+ // Create global config directory
18
+ const globalConfigDir = path.join(os.homedir(), '.snow-flow');
19
+ if (!fs.existsSync(globalConfigDir)) {
20
+ fs.mkdirSync(globalConfigDir, { recursive: true });
21
+ console.log(`āœ… Created global config directory at ${globalConfigDir}`);
22
+ }
23
+ } else {
24
+ // Local installation - don't create directories automatically
25
+ console.log('āœ… Snow-Flow installed locally');
26
+ console.log('šŸ”§ Run "snow-flow init" to initialize your project');
27
+ }
28
+
29
+ console.log('\nšŸ“š Documentation: https://github.com/groeimetai/snow-flow#readme');
30
+ console.log('šŸ†˜ Get help: snow-flow --help');
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Update version.ts with the current version from package.json
5
+ * This script runs automatically after npm version
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+
11
+ // Read package.json
12
+ const packageJsonPath = path.join(__dirname, '..', 'package.json');
13
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
14
+ const version = packageJson.version;
15
+
16
+ // Path to version.ts
17
+ const versionTsPath = path.join(__dirname, '..', 'src', 'version.ts');
18
+
19
+ // Read current version.ts content
20
+ const versionTsContent = fs.readFileSync(versionTsPath, 'utf8');
21
+
22
+ // Replace the VERSION constant
23
+ const updatedContent = versionTsContent.replace(
24
+ /export const VERSION = '[^']+';/,
25
+ `export const VERSION = '${version}';`
26
+ );
27
+
28
+ // Write updated content back
29
+ fs.writeFileSync(versionTsPath, updatedContent, 'utf8');
30
+
31
+ console.log(`āœ… Updated version.ts to ${version}`);