claude-flow 2.0.0-alpha.85 → 2.0.0-alpha.87

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 (133) hide show
  1. package/.claude/checkpoints/1754403519.json +1 -0
  2. package/.claude/checkpoints/1754403521.json +1 -0
  3. package/.claude/checkpoints/1754403535.json +1 -0
  4. package/.claude/checkpoints/1754403536.json +1 -0
  5. package/.claude/checkpoints/1754403546.json +1 -0
  6. package/.claude/checkpoints/1754403548.json +1 -0
  7. package/.claude/checkpoints/1754403559.json +1 -0
  8. package/.claude/checkpoints/1754403561.json +1 -0
  9. package/.claude/checkpoints/1754403570.json +1 -0
  10. package/.claude/checkpoints/1754403572.json +1 -0
  11. package/.claude/checkpoints/1754403590.json +1 -0
  12. package/.claude/checkpoints/1754403592.json +1 -0
  13. package/.claude/checkpoints/1754403629.json +1 -0
  14. package/.claude/checkpoints/1754403631.json +1 -0
  15. package/.claude/checkpoints/1754403662.json +1 -0
  16. package/.claude/checkpoints/1754403664.json +1 -0
  17. package/.claude/checkpoints/1754403748.json +1 -0
  18. package/.claude/checkpoints/1754403749.json +1 -0
  19. package/.claude/checkpoints/1754404006.json +1 -0
  20. package/.claude/checkpoints/1754404008.json +1 -0
  21. package/.claude/checkpoints/1754404015.json +1 -0
  22. package/.claude/checkpoints/1754404017.json +1 -0
  23. package/.claude/checkpoints/1754404029.json +1 -0
  24. package/.claude/checkpoints/1754404031.json +1 -0
  25. package/.claude/checkpoints/1754404054.json +1 -0
  26. package/.claude/checkpoints/1754404055.json +1 -0
  27. package/.claude/checkpoints/1754404074.json +1 -0
  28. package/.claude/checkpoints/1754404075.json +1 -0
  29. package/.claude/checkpoints/1754404152.json +1 -0
  30. package/.claude/checkpoints/1754404154.json +1 -0
  31. package/.claude/checkpoints/1754404164.json +1 -0
  32. package/.claude/checkpoints/1754404165.json +1 -0
  33. package/.claude/checkpoints/1754404207.json +1 -0
  34. package/.claude/checkpoints/1754404209.json +1 -0
  35. package/.claude/checkpoints/1754422767.json +1 -0
  36. package/.claude/checkpoints/1754422769.json +1 -0
  37. package/.claude/checkpoints/1754422789.json +1 -0
  38. package/.claude/checkpoints/1754422791.json +1 -0
  39. package/.claude/checkpoints/1754422833.json +1 -0
  40. package/.claude/checkpoints/1754422834.json +1 -0
  41. package/.claude/checkpoints/1754422869.json +1 -0
  42. package/.claude/checkpoints/1754422871.json +1 -0
  43. package/.claude/checkpoints/1754422990.json +1 -0
  44. package/.claude/checkpoints/1754422992.json +1 -0
  45. package/.claude/checkpoints/1754424457.json +1 -0
  46. package/.claude/checkpoints/1754424458.json +1 -0
  47. package/.claude/checkpoints/1754424471.json +1 -0
  48. package/.claude/checkpoints/1754424473.json +1 -0
  49. package/.claude/checkpoints/1754424499.json +1 -0
  50. package/.claude/checkpoints/1754424500.json +1 -0
  51. package/.claude/checkpoints/1754424506.json +1 -0
  52. package/.claude/checkpoints/1754424508.json +1 -0
  53. package/.claude/checkpoints/1754424531.json +1 -0
  54. package/.claude/checkpoints/1754424532.json +1 -0
  55. package/.claude/checkpoints/1754424547.json +1 -0
  56. package/.claude/checkpoints/1754424549.json +1 -0
  57. package/.claude/checkpoints/1754424621.json +1 -0
  58. package/.claude/checkpoints/1754424622.json +1 -0
  59. package/.claude/checkpoints/1754424634.json +1 -0
  60. package/.claude/checkpoints/1754424635.json +1 -0
  61. package/.claude/checkpoints/1754424651.json +1 -0
  62. package/.claude/checkpoints/1754424652.json +1 -0
  63. package/.claude/checkpoints/1754424659.json +1 -0
  64. package/.claude/checkpoints/1754424661.json +1 -0
  65. package/.claude/checkpoints/1754424669.json +1 -0
  66. package/.claude/checkpoints/1754424671.json +1 -0
  67. package/.claude/checkpoints/1754424678.json +1 -0
  68. package/.claude/checkpoints/1754424680.json +1 -0
  69. package/.claude/checkpoints/1754424691.json +1 -0
  70. package/.claude/checkpoints/1754424693.json +1 -0
  71. package/.claude/checkpoints/1754424705.json +1 -0
  72. package/.claude/checkpoints/1754424706.json +1 -0
  73. package/.claude/checkpoints/1754424797.json +1 -0
  74. package/.claude/checkpoints/1754424798.json +1 -0
  75. package/.claude/checkpoints/1754424810.json +1 -0
  76. package/.claude/checkpoints/1754424812.json +1 -0
  77. package/.claude/checkpoints/1754424818.json +1 -0
  78. package/.claude/checkpoints/1754424820.json +1 -0
  79. package/.claude/checkpoints/1754425153.json +1 -0
  80. package/.claude/checkpoints/1754425155.json +1 -0
  81. package/.claude/checkpoints/summary-session-20250805-130533.md +747 -0
  82. package/.claude/checkpoints/summary-session-20250805-131013.md +751 -0
  83. package/.claude/checkpoints/summary-session-20250805-134756.md +702 -0
  84. package/.claude/checkpoints/summary-session-20250805-135408.md +700 -0
  85. package/.claude/checkpoints/summary-session-20250805-193618.md +542 -0
  86. package/.claude/checkpoints/summary-session-20250805-194451.md +574 -0
  87. package/.claude/checkpoints/summary-session-20250805-194932.md +582 -0
  88. package/.claude/checkpoints/summary-session-20250805-201358.md +1050 -0
  89. package/.claude/checkpoints/summary-session-20250805-201545.md +1057 -0
  90. package/.claude/checkpoints/summary-session-20250805-201634.md +1060 -0
  91. package/.claude/checkpoints/summary-session-20250805-202405.md +1069 -0
  92. package/.claude/checkpoints/task-1754399200.json +1 -0
  93. package/.claude/checkpoints/task-1754401597.json +1 -0
  94. package/.claude/checkpoints/task-1754401875.json +1 -0
  95. package/.claude/checkpoints/task-1754403259.json +1 -0
  96. package/.claude/checkpoints/task-1754422400.json +1 -0
  97. package/.claude/checkpoints/task-1754422444.json +1 -0
  98. package/.claude/checkpoints/task-1754422455.json +1 -0
  99. package/.claude/checkpoints/task-1754422536.json +1 -0
  100. package/.claude/checkpoints/task-1754422724.json +1 -0
  101. package/.claude/checkpoints/task-1754422854.json +1 -0
  102. package/.claude/checkpoints/task-1754422974.json +1 -0
  103. package/.claude/checkpoints/task-1754423111.json +1 -0
  104. package/.claude/checkpoints/task-1754423117.json +1 -0
  105. package/.claude/checkpoints/task-1754424313.json +1 -0
  106. package/.claude/checkpoints/task-1754424604.json +1 -0
  107. package/.claude/checkpoints/task-1754424741.json +1 -0
  108. package/.claude/checkpoints/task-1754424873.json +1 -0
  109. package/.claude/checkpoints/task-1754424930.json +1 -0
  110. package/.claude/checkpoints/task-1754424980.json +1 -0
  111. package/.claude/checkpoints/task-1754425127.json +1 -0
  112. package/.claude/checkpoints/task-1754425201.json +1 -0
  113. package/.claude/checkpoints/task-1754425469.json +1 -0
  114. package/CHANGELOG.md +43 -0
  115. package/bin/claude-flow +1 -1
  116. package/bin/claude-flow.js +6 -4
  117. package/package.json +1 -1
  118. package/src/cli/command-registry.js +27 -0
  119. package/src/cli/commands/hive-mind/pause.ts +1 -1
  120. package/src/cli/commands/hive-mind/stop.ts +3 -3
  121. package/src/cli/commands/status.ts +2 -1
  122. package/src/cli/help-text.js +3 -2
  123. package/src/cli/index-remote.ts +1 -1
  124. package/src/cli/index.ts +1 -4
  125. package/src/cli/simple-cli.js +1 -2
  126. package/src/cli/simple-cli.ts +1 -2
  127. package/src/cli/simple-commands/hive-mind.js +2 -2
  128. package/src/cli/simple-commands/init/index.js +1 -1
  129. package/src/cli/simple-commands/memory-consolidation.js +632 -0
  130. package/src/cli/simple-commands/memory.js +35 -22
  131. package/src/core/version.js +41 -0
  132. package/src/core/version.ts +41 -0
  133. package/src/memory/unified-memory-manager.js +461 -0
@@ -0,0 +1,632 @@
1
+ // memory-consolidation.js - Database consolidation utility
2
+ import { printSuccess, printError, printWarning, printInfo } from '../utils.js';
3
+ import { promises as fs } from 'fs';
4
+ import path from 'path';
5
+ import { existsSync } from '../node-compat.js';
6
+ // Dynamic imports for optional dependencies
7
+ let sqlite3;
8
+ let sqliteOpen;
9
+
10
+ async function loadSqliteModules() {
11
+ try {
12
+ const sqlite3Module = await import('sqlite3');
13
+ sqlite3 = sqlite3Module.default;
14
+ const sqliteModule = await import('sqlite');
15
+ sqliteOpen = sqliteModule.open;
16
+ return true;
17
+ } catch (err) {
18
+ return false;
19
+ }
20
+ }
21
+
22
+ /**
23
+ * Memory database consolidation strategy
24
+ * Consolidates multiple memory storage locations into a unified structure
25
+ */
26
+ export class MemoryConsolidator {
27
+ constructor() {
28
+ this.primaryLocations = {
29
+ json: './memory/memory-store.json',
30
+ sqlite: './.claude-flow/memory/unified-memory.db',
31
+ backup: './.claude-flow/memory/backups/'
32
+ };
33
+
34
+ this.knownLocations = [
35
+ // JSON stores
36
+ './memory/memory-store.json',
37
+ './.claude-flow/memory/store.json',
38
+
39
+ // SQLite databases
40
+ './.swarm/memory.db',
41
+ './.hive-mind/memory.db',
42
+ './.hive-mind/hive.db',
43
+ './.ruv-swarm/swarm.db',
44
+ './data/hive-mind.db',
45
+
46
+ // Legacy locations
47
+ './memory.json',
48
+ './data/memory.json'
49
+ ];
50
+ }
51
+
52
+ /**
53
+ * Scan for all memory storage locations
54
+ */
55
+ async scanMemoryLocations() {
56
+ const found = {
57
+ json: [],
58
+ sqlite: [],
59
+ total: 0,
60
+ sizeBytes: 0
61
+ };
62
+
63
+ // Check known locations
64
+ for (const location of this.knownLocations) {
65
+ if (existsSync(location)) {
66
+ const stats = await fs.stat(location);
67
+ const type = location.endsWith('.db') ? 'sqlite' : 'json';
68
+
69
+ found[type].push({
70
+ path: location,
71
+ size: stats.size,
72
+ modified: stats.mtime
73
+ });
74
+
75
+ found.total++;
76
+ found.sizeBytes += stats.size;
77
+ }
78
+ }
79
+
80
+ // Scan for additional .db files
81
+ try {
82
+ const dbFiles = await this.findDatabaseFiles('.');
83
+ for (const dbFile of dbFiles) {
84
+ if (!this.knownLocations.includes(dbFile)) {
85
+ const stats = await fs.stat(dbFile);
86
+ found.sqlite.push({
87
+ path: dbFile,
88
+ size: stats.size,
89
+ modified: stats.mtime
90
+ });
91
+ found.total++;
92
+ found.sizeBytes += stats.size;
93
+ }
94
+ }
95
+ } catch (err) {
96
+ // Ignore scan errors
97
+ }
98
+
99
+ return found;
100
+ }
101
+
102
+ /**
103
+ * Find all .db files recursively
104
+ */
105
+ async findDatabaseFiles(dir, files = []) {
106
+ try {
107
+ const items = await fs.readdir(dir);
108
+
109
+ for (const item of items) {
110
+ // Skip node_modules and hidden directories
111
+ if (item === 'node_modules' || item.startsWith('.git')) continue;
112
+
113
+ const fullPath = path.join(dir, item);
114
+ const stat = await fs.stat(fullPath);
115
+
116
+ if (stat.isDirectory() && item.startsWith('.')) {
117
+ // Check hidden directories for db files
118
+ await this.findDatabaseFiles(fullPath, files);
119
+ } else if (item.endsWith('.db')) {
120
+ files.push(fullPath);
121
+ }
122
+ }
123
+ } catch (err) {
124
+ // Ignore permission errors
125
+ }
126
+
127
+ return files;
128
+ }
129
+
130
+ /**
131
+ * Create consolidation plan
132
+ */
133
+ async createConsolidationPlan(locations) {
134
+ const plan = {
135
+ steps: [],
136
+ estimatedTime: 0,
137
+ totalData: locations.sizeBytes,
138
+ backupRequired: locations.total > 0
139
+ };
140
+
141
+ // Step 1: Backup existing data
142
+ if (plan.backupRequired) {
143
+ plan.steps.push({
144
+ action: 'backup',
145
+ description: 'Create backups of all existing memory stores',
146
+ sources: [...locations.json, ...locations.sqlite].map(l => l.path),
147
+ destination: this.primaryLocations.backup
148
+ });
149
+ plan.estimatedTime += 2; // seconds
150
+ }
151
+
152
+ // Step 2: Convert JSON stores to unified format
153
+ if (locations.json.length > 0) {
154
+ plan.steps.push({
155
+ action: 'convert-json',
156
+ description: 'Convert JSON memory stores to unified format',
157
+ sources: locations.json.map(l => l.path),
158
+ destination: this.primaryLocations.sqlite
159
+ });
160
+ plan.estimatedTime += locations.json.length * 1;
161
+ }
162
+
163
+ // Step 3: Merge SQLite databases
164
+ if (locations.sqlite.length > 0) {
165
+ plan.steps.push({
166
+ action: 'merge-sqlite',
167
+ description: 'Merge SQLite databases into unified store',
168
+ sources: locations.sqlite.map(l => l.path),
169
+ destination: this.primaryLocations.sqlite
170
+ });
171
+ plan.estimatedTime += locations.sqlite.length * 2;
172
+ }
173
+
174
+ // Step 4: Create indices for performance
175
+ plan.steps.push({
176
+ action: 'optimize',
177
+ description: 'Create indices and optimize unified database',
178
+ destination: this.primaryLocations.sqlite
179
+ });
180
+ plan.estimatedTime += 1;
181
+
182
+ // Step 5: Update configuration
183
+ plan.steps.push({
184
+ action: 'update-config',
185
+ description: 'Update memory configuration to use unified store',
186
+ config: {
187
+ memoryStore: this.primaryLocations.sqlite,
188
+ backupLocation: this.primaryLocations.backup,
189
+ legacySupport: true
190
+ }
191
+ });
192
+
193
+ return plan;
194
+ }
195
+
196
+ /**
197
+ * Execute consolidation plan
198
+ */
199
+ async executeConsolidation(plan, options = {}) {
200
+ const results = {
201
+ success: false,
202
+ stepsCompleted: 0,
203
+ errors: [],
204
+ backupPath: null,
205
+ newStorePath: null
206
+ };
207
+
208
+ try {
209
+ for (const step of plan.steps) {
210
+ printInfo(`Executing: ${step.description}`);
211
+
212
+ switch (step.action) {
213
+ case 'backup':
214
+ results.backupPath = await this.createBackups(step.sources, step.destination);
215
+ break;
216
+
217
+ case 'convert-json':
218
+ await this.convertJsonToSqlite(step.sources, step.destination);
219
+ break;
220
+
221
+ case 'merge-sqlite':
222
+ await this.mergeSqliteDatabases(step.sources, step.destination);
223
+ break;
224
+
225
+ case 'optimize':
226
+ await this.optimizeDatabase(step.destination);
227
+ break;
228
+
229
+ case 'update-config':
230
+ await this.updateConfiguration(step.config);
231
+ break;
232
+ }
233
+
234
+ results.stepsCompleted++;
235
+ printSuccess(`✓ ${step.description}`);
236
+ }
237
+
238
+ results.success = true;
239
+ results.newStorePath = this.primaryLocations.sqlite;
240
+
241
+ } catch (err) {
242
+ results.errors.push(err.message);
243
+ printError(`Failed at step ${results.stepsCompleted + 1}: ${err.message}`);
244
+ }
245
+
246
+ return results;
247
+ }
248
+
249
+ /**
250
+ * Create backups of all memory stores
251
+ */
252
+ async createBackups(sources, backupDir) {
253
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
254
+ const backupPath = path.join(backupDir, `backup-${timestamp}`);
255
+
256
+ await fs.mkdir(backupPath, { recursive: true });
257
+
258
+ for (const source of sources) {
259
+ if (existsSync(source)) {
260
+ const filename = path.basename(source);
261
+ const dest = path.join(backupPath, filename);
262
+ await fs.copyFile(source, dest);
263
+ }
264
+ }
265
+
266
+ return backupPath;
267
+ }
268
+
269
+ /**
270
+ * Convert JSON memory stores to SQLite
271
+ */
272
+ async convertJsonToSqlite(jsonFiles, dbPath) {
273
+ if (!sqlite3 || !sqliteOpen) {
274
+ throw new Error('SQLite modules not available. Install sqlite3 and sqlite packages.');
275
+ }
276
+
277
+ await fs.mkdir(path.dirname(dbPath), { recursive: true });
278
+
279
+ const db = await sqliteOpen({
280
+ filename: dbPath,
281
+ driver: sqlite3.Database
282
+ });
283
+
284
+ // Create unified schema
285
+ await db.exec(`
286
+ CREATE TABLE IF NOT EXISTS memory_entries (
287
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
288
+ key TEXT NOT NULL,
289
+ value TEXT NOT NULL,
290
+ namespace TEXT NOT NULL DEFAULT 'default',
291
+ timestamp INTEGER NOT NULL,
292
+ source TEXT,
293
+ UNIQUE(key, namespace)
294
+ );
295
+
296
+ CREATE INDEX IF NOT EXISTS idx_namespace ON memory_entries(namespace);
297
+ CREATE INDEX IF NOT EXISTS idx_timestamp ON memory_entries(timestamp);
298
+ CREATE INDEX IF NOT EXISTS idx_key ON memory_entries(key);
299
+ `);
300
+
301
+ // Import each JSON file
302
+ for (const jsonFile of jsonFiles) {
303
+ if (!existsSync(jsonFile)) continue;
304
+
305
+ try {
306
+ const content = await fs.readFile(jsonFile, 'utf8');
307
+ const data = JSON.parse(content);
308
+
309
+ const stmt = await db.prepare(`
310
+ INSERT OR REPLACE INTO memory_entries (key, value, namespace, timestamp, source)
311
+ VALUES (?, ?, ?, ?, ?)
312
+ `);
313
+
314
+ for (const [namespace, entries] of Object.entries(data)) {
315
+ for (const entry of entries) {
316
+ await stmt.run(
317
+ entry.key,
318
+ entry.value,
319
+ entry.namespace || namespace,
320
+ entry.timestamp,
321
+ jsonFile
322
+ );
323
+ }
324
+ }
325
+
326
+ await stmt.finalize();
327
+ } catch (err) {
328
+ printWarning(`Failed to import ${jsonFile}: ${err.message}`);
329
+ }
330
+ }
331
+
332
+ await db.close();
333
+ }
334
+
335
+ /**
336
+ * Merge multiple SQLite databases
337
+ */
338
+ async mergeSqliteDatabases(dbFiles, targetDb) {
339
+ if (!sqlite3 || !sqliteOpen) {
340
+ throw new Error('SQLite modules not available. Install sqlite3 and sqlite packages.');
341
+ }
342
+
343
+ const db = await sqliteOpen({
344
+ filename: targetDb,
345
+ driver: sqlite3.Database
346
+ });
347
+
348
+ for (const dbFile of dbFiles) {
349
+ if (!existsSync(dbFile) || dbFile === targetDb) continue;
350
+
351
+ try {
352
+ // Attach the source database
353
+ const alias = `db_${path.basename(dbFile, '.db')}`;
354
+ await db.exec(`ATTACH DATABASE '${dbFile}' AS ${alias}`);
355
+
356
+ // Get tables from source database
357
+ const tables = await db.all(`
358
+ SELECT name FROM ${alias}.sqlite_master
359
+ WHERE type='table' AND name LIKE '%memory%'
360
+ `);
361
+
362
+ // Copy data from each memory-related table
363
+ for (const table of tables) {
364
+ try {
365
+ await db.exec(`
366
+ INSERT OR IGNORE INTO memory_entries (key, value, namespace, timestamp, source)
367
+ SELECT
368
+ COALESCE(key, ''),
369
+ COALESCE(value, ''),
370
+ COALESCE(namespace, 'default'),
371
+ COALESCE(timestamp, strftime('%s', 'now') * 1000),
372
+ '${dbFile}'
373
+ FROM ${alias}.${table.name}
374
+ WHERE key IS NOT NULL AND value IS NOT NULL
375
+ `);
376
+ } catch (err) {
377
+ // Table structure might be different, skip
378
+ }
379
+ }
380
+
381
+ await db.exec(`DETACH DATABASE ${alias}`);
382
+ } catch (err) {
383
+ printWarning(`Failed to merge ${dbFile}: ${err.message}`);
384
+ }
385
+ }
386
+
387
+ await db.close();
388
+ }
389
+
390
+ /**
391
+ * Optimize the unified database
392
+ */
393
+ async optimizeDatabase(dbPath) {
394
+ if (!sqlite3 || !sqliteOpen) {
395
+ throw new Error('SQLite modules not available. Install sqlite3 and sqlite packages.');
396
+ }
397
+
398
+ const db = await sqliteOpen({
399
+ filename: dbPath,
400
+ driver: sqlite3.Database
401
+ });
402
+
403
+ // Add performance optimizations
404
+ await db.exec(`
405
+ -- Enable Write-Ahead Logging for better performance
406
+ PRAGMA journal_mode = WAL;
407
+ PRAGMA synchronous = NORMAL;
408
+
409
+ -- Optimize database
410
+ VACUUM;
411
+ ANALYZE;
412
+
413
+ -- Create additional indices for common queries
414
+ CREATE INDEX IF NOT EXISTS idx_key_value ON memory_entries(key, value);
415
+ CREATE INDEX IF NOT EXISTS idx_namespace_timestamp ON memory_entries(namespace, timestamp);
416
+ `);
417
+
418
+ await db.close();
419
+ }
420
+
421
+ /**
422
+ * Update configuration to use unified store
423
+ */
424
+ async updateConfiguration(config) {
425
+ const configPath = './.claude-flow/memory-config.json';
426
+
427
+ await fs.mkdir(path.dirname(configPath), { recursive: true });
428
+ await fs.writeFile(configPath, JSON.stringify(config, null, 2));
429
+
430
+ // Create symlinks for backward compatibility
431
+ if (config.legacySupport) {
432
+ try {
433
+ // Create symlink from old JSON location to new
434
+ if (existsSync('./memory/memory-store.json')) {
435
+ await fs.rename('./memory/memory-store.json', './memory/memory-store.json.old');
436
+ }
437
+ // Note: We don't create actual symlinks to SQLite as JSON/SQLite formats differ
438
+ // Instead, the memory manager will check the config and use the unified store
439
+ } catch (err) {
440
+ // Ignore symlink errors
441
+ }
442
+ }
443
+ }
444
+
445
+ /**
446
+ * Generate consolidation report
447
+ */
448
+ generateReport(scanResults, plan, executionResults) {
449
+ const report = [];
450
+
451
+ report.push('📊 Memory Consolidation Report');
452
+ report.push('================================\n');
453
+
454
+ report.push('📁 Discovered Memory Stores:');
455
+ report.push(` • JSON files: ${scanResults.json.length}`);
456
+ report.push(` • SQLite databases: ${scanResults.sqlite.length}`);
457
+ report.push(` • Total size: ${(scanResults.sizeBytes / 1024 / 1024).toFixed(2)} MB\n`);
458
+
459
+ report.push('📋 Consolidation Plan:');
460
+ for (const step of plan.steps) {
461
+ report.push(` ✓ ${step.description}`);
462
+ }
463
+ report.push(` • Estimated time: ${plan.estimatedTime} seconds\n`);
464
+
465
+ if (executionResults) {
466
+ report.push('✅ Execution Results:');
467
+ report.push(` • Success: ${executionResults.success ? 'Yes' : 'No'}`);
468
+ report.push(` • Steps completed: ${executionResults.stepsCompleted}/${plan.steps.length}`);
469
+
470
+ if (executionResults.backupPath) {
471
+ report.push(` • Backup location: ${executionResults.backupPath}`);
472
+ }
473
+
474
+ if (executionResults.newStorePath) {
475
+ report.push(` • Unified store: ${executionResults.newStorePath}`);
476
+ }
477
+
478
+ if (executionResults.errors.length > 0) {
479
+ report.push('\n❌ Errors:');
480
+ for (const error of executionResults.errors) {
481
+ report.push(` • ${error}`);
482
+ }
483
+ }
484
+ }
485
+
486
+ return report.join('\n');
487
+ }
488
+ }
489
+
490
+ /**
491
+ * Memory consolidation command
492
+ */
493
+ export async function memoryConsolidationCommand(subArgs, flags) {
494
+ // Load SQLite modules if available
495
+ const sqliteAvailable = await loadSqliteModules();
496
+
497
+ const consolidator = new MemoryConsolidator();
498
+ const action = subArgs[0];
499
+
500
+ switch (action) {
501
+ case 'scan':
502
+ await scanMemoryStores(consolidator);
503
+ break;
504
+
505
+ case 'plan':
506
+ await createConsolidationPlan(consolidator);
507
+ break;
508
+
509
+ case 'execute':
510
+ await executeConsolidation(consolidator, flags);
511
+ break;
512
+
513
+ case 'report':
514
+ await generateConsolidationReport(consolidator);
515
+ break;
516
+
517
+ default:
518
+ showConsolidationHelp();
519
+ }
520
+ }
521
+
522
+ async function scanMemoryStores(consolidator) {
523
+ printInfo('Scanning for memory storage locations...');
524
+
525
+ const results = await consolidator.scanMemoryLocations();
526
+
527
+ printSuccess(`Found ${results.total} memory storage locations:`);
528
+
529
+ if (results.json.length > 0) {
530
+ console.log('\n📄 JSON Stores:');
531
+ for (const store of results.json) {
532
+ console.log(` • ${store.path} (${(store.size / 1024).toFixed(1)} KB)`);
533
+ }
534
+ }
535
+
536
+ if (results.sqlite.length > 0) {
537
+ console.log('\n🗄️ SQLite Databases:');
538
+ for (const db of results.sqlite) {
539
+ console.log(` • ${db.path} (${(db.size / 1024).toFixed(1)} KB)`);
540
+ }
541
+ }
542
+
543
+ console.log(`\n💾 Total size: ${(results.sizeBytes / 1024 / 1024).toFixed(2)} MB`);
544
+ }
545
+
546
+ async function createConsolidationPlan(consolidator) {
547
+ const scanResults = await consolidator.scanMemoryLocations();
548
+ const plan = await consolidator.createConsolidationPlan(scanResults);
549
+
550
+ printSuccess('📋 Consolidation Plan Created:');
551
+
552
+ for (let i = 0; i < plan.steps.length; i++) {
553
+ const step = plan.steps[i];
554
+ console.log(`\n${i + 1}. ${step.description}`);
555
+
556
+ if (step.sources) {
557
+ console.log(' Sources:');
558
+ for (const source of step.sources) {
559
+ console.log(` • ${source}`);
560
+ }
561
+ }
562
+
563
+ if (step.destination) {
564
+ console.log(` Destination: ${step.destination}`);
565
+ }
566
+ }
567
+
568
+ console.log(`\n⏱️ Estimated time: ${plan.estimatedTime} seconds`);
569
+ console.log('\nRun "memory-consolidate execute" to perform consolidation');
570
+ }
571
+
572
+ async function executeConsolidation(consolidator, flags) {
573
+ const sqliteAvailable = await loadSqliteModules();
574
+
575
+ if (!sqliteAvailable) {
576
+ printError('SQLite modules not available.');
577
+ printInfo('Install required packages: npm install sqlite3 sqlite');
578
+ return;
579
+ }
580
+
581
+ const scanResults = await consolidator.scanMemoryLocations();
582
+
583
+ if (scanResults.total === 0) {
584
+ printWarning('No memory stores found to consolidate');
585
+ return;
586
+ }
587
+
588
+ const plan = await consolidator.createConsolidationPlan(scanResults);
589
+
590
+ if (!flags.force) {
591
+ printWarning('This will consolidate all memory stores into a unified database.');
592
+ printWarning('A backup will be created before any changes are made.');
593
+ console.log('\nUse --force flag to proceed without confirmation');
594
+ return;
595
+ }
596
+
597
+ printInfo('Starting memory consolidation...');
598
+ const results = await consolidator.executeConsolidation(plan);
599
+
600
+ const report = consolidator.generateReport(scanResults, plan, results);
601
+ console.log('\n' + report);
602
+
603
+ if (results.success) {
604
+ printSuccess('\n✅ Memory consolidation completed successfully!');
605
+ console.log(`Unified store location: ${results.newStorePath}`);
606
+ } else {
607
+ printError('\n❌ Memory consolidation failed');
608
+ console.log('Check the errors above and try again');
609
+ }
610
+ }
611
+
612
+ async function generateConsolidationReport(consolidator) {
613
+ const scanResults = await consolidator.scanMemoryLocations();
614
+ const plan = await consolidator.createConsolidationPlan(scanResults);
615
+
616
+ const report = consolidator.generateReport(scanResults, plan);
617
+ console.log(report);
618
+ }
619
+
620
+ function showConsolidationHelp() {
621
+ console.log('Memory consolidation commands:');
622
+ console.log(' scan Scan for all memory storage locations');
623
+ console.log(' plan Create a consolidation plan');
624
+ console.log(' execute Execute the consolidation (use --force to skip confirmation)');
625
+ console.log(' report Generate a consolidation report');
626
+ console.log();
627
+ console.log('Examples:');
628
+ console.log(' memory-consolidate scan');
629
+ console.log(' memory-consolidate plan');
630
+ console.log(' memory-consolidate execute --force');
631
+ console.log(' memory-consolidate report');
632
+ }