stigmergy 1.2.6 → 1.2.8

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 (59) hide show
  1. package/README.md +32 -17
  2. package/STIGMERGY.md +16 -7
  3. package/docs/MULTI_USER_WIKI_COLLABORATION_SYSTEM.md +523 -0
  4. package/docs/PROMPT_BASED_SKILLS_SYSTEM_DESIGN.md +458 -0
  5. package/docs/SKILL_IMPLEMENTATION_CONSTRAINTS_AND_ALIGNMENT.md +423 -0
  6. package/docs/TECHNICAL_FEASIBILITY_ANALYSIS.md +308 -0
  7. package/examples/multilingual-hook-demo.js +125 -0
  8. package/package.json +14 -17
  9. package/scripts/dependency-analyzer.js +101 -0
  10. package/scripts/generate-cli-docs.js +64 -0
  11. package/scripts/postuninstall.js +46 -0
  12. package/scripts/preuninstall.js +75 -0
  13. package/scripts/run-layered-tests.js +3 -3
  14. package/src/adapters/claude/install_claude_integration.js +17 -17
  15. package/src/adapters/codebuddy/install_codebuddy_integration.js +13 -13
  16. package/src/adapters/codex/install_codex_integration.js +27 -27
  17. package/src/adapters/copilot/install_copilot_integration.js +46 -46
  18. package/src/adapters/gemini/install_gemini_integration.js +10 -10
  19. package/src/adapters/iflow/install_iflow_integration.js +7 -7
  20. package/src/adapters/qoder/install_qoder_integration.js +12 -12
  21. package/src/adapters/qwen/install_qwen_integration.js +17 -17
  22. package/src/auth.js +173 -173
  23. package/src/auth_command.js +208 -208
  24. package/src/calculator.js +313 -313
  25. package/src/cli/router.js +151 -7
  26. package/src/core/cache_cleaner.js +767 -767
  27. package/src/core/cli_help_analyzer.js +680 -680
  28. package/src/core/cli_parameter_handler.js +132 -132
  29. package/src/core/cli_tools.js +89 -89
  30. package/src/core/coordination/index.js +16 -16
  31. package/src/core/coordination/nodejs/AdapterManager.js +102 -102
  32. package/src/core/coordination/nodejs/CLCommunication.js +132 -132
  33. package/src/core/coordination/nodejs/CLIIntegrationManager.js +272 -272
  34. package/src/core/coordination/nodejs/HealthChecker.js +76 -76
  35. package/src/core/coordination/nodejs/HookDeploymentManager.js +463 -274
  36. package/src/core/coordination/nodejs/StatisticsCollector.js +71 -71
  37. package/src/core/coordination/nodejs/index.js +90 -90
  38. package/src/core/coordination/nodejs/utils/Logger.js +29 -29
  39. package/src/core/enhanced_installer.js +479 -479
  40. package/src/core/enhanced_uninstaller.js +638 -638
  41. package/src/core/error_handler.js +406 -406
  42. package/src/core/installer.js +32 -32
  43. package/src/core/memory_manager.js +83 -83
  44. package/src/core/multilingual/language-pattern-manager.js +172 -0
  45. package/src/core/rest_client.js +160 -160
  46. package/src/core/smart_router.js +261 -249
  47. package/src/core/upgrade_manager.js +48 -20
  48. package/src/data_encryption.js +143 -143
  49. package/src/data_structures.js +440 -440
  50. package/src/deploy.js +55 -55
  51. package/src/index.js +30 -30
  52. package/src/test/cli-availability-checker.js +194 -194
  53. package/src/test/test-environment.js +289 -289
  54. package/src/utils/helpers.js +35 -35
  55. package/src/utils.js +921 -921
  56. package/src/weatherProcessor.js +228 -228
  57. package/test/multilingual/hook-deployment.test.js +91 -0
  58. package/test/multilingual/language-pattern-manager.test.js +140 -0
  59. package/test/multilingual/system-test.js +85 -0
@@ -1,767 +1,767 @@
1
- /**
2
- * Comprehensive Cache Cleaner for Stigmergy
3
- *
4
- * Intelligent cache cleaning with selective removal, performance optimization,
5
- * and error recovery capabilities.
6
- */
7
-
8
- const fs = require('fs');
9
- const path = require('path');
10
- const os = require('os');
11
- const { spawnSync } = require('child_process');
12
-
13
- class CacheCleaner {
14
- constructor(options = {}) {
15
- this.options = {
16
- dryRun: options.dryRun || false,
17
- force: options.force || false,
18
- verbose: options.verbose || false,
19
- preserveRecent: options.preserveRecent || 24 * 60 * 60 * 1000, // 24 hours
20
- batchSize: options.batchSize || 50,
21
- parallel: options.parallel || true,
22
- ...options,
23
- };
24
-
25
- this.homeDir = os.homedir();
26
- this.results = {
27
- filesRemoved: 0,
28
- directoriesRemoved: 0,
29
- bytesFreed: 0,
30
- errors: [],
31
- skipped: [],
32
- };
33
- }
34
-
35
- /**
36
- * Clean all caches comprehensively
37
- */
38
- async cleanAllCaches(options = {}) {
39
- const config = {
40
- cleanStigmergy: true,
41
- cleanNPX: true,
42
- cleanNPM: true,
43
- cleanCLI: true,
44
- cleanTemp: true,
45
- ...options,
46
- };
47
-
48
- console.log('🧹 Starting Comprehensive Cache Cleaning...\n');
49
-
50
- if (this.options.dryRun) {
51
- console.log('šŸ” DRY RUN MODE - No files will be deleted\n');
52
- }
53
-
54
- try {
55
- // 1. Clean Stigmergy cache
56
- if (config.cleanStigmergy) {
57
- await this.cleanStigmergyCache();
58
- }
59
-
60
- // 2. Clean NPX cache
61
- if (config.cleanNPX) {
62
- await this.cleanNPXCache();
63
- }
64
-
65
- // 3. Clean NPM cache
66
- if (config.cleanNPM) {
67
- await this.cleanNPMCache();
68
- }
69
-
70
- // 4. Clean CLI configurations
71
- if (config.cleanCLI) {
72
- await this.cleanCLIConfigurations();
73
- }
74
-
75
- // 5. Clean temporary files
76
- if (config.cleanTemp) {
77
- await this.cleanTemporaryFiles();
78
- }
79
-
80
- // 6. Print summary
81
- this.printSummary();
82
-
83
- return this.results;
84
- } catch (error) {
85
- console.error('ļæ½?Cache cleaning failed:', error.message);
86
- this.results.errors.push(error.message);
87
- return this.results;
88
- }
89
- }
90
-
91
- /**
92
- * Clean Stigmergy cache and temporary files
93
- */
94
- async cleanStigmergyCache() {
95
- console.log('šŸ“ Cleaning Stigmergy cache...');
96
-
97
- const stigmergyDir = path.join(this.homeDir, '.stigmergy');
98
- const testDir = path.join(this.homeDir, '.stigmergy-test');
99
-
100
- // Clean main cache directory
101
- if (fs.existsSync(stigmergyDir)) {
102
- await this.cleanStigmergyDirectory(stigmergyDir, 'main');
103
- }
104
-
105
- // Clean test directory
106
- if (fs.existsSync(testDir)) {
107
- await this.cleanStigmergyDirectory(testDir, 'test');
108
- }
109
-
110
- // Clean cache subdirectories specifically
111
- const cachePaths = [
112
- path.join(stigmergyDir, 'cache'),
113
- path.join(stigmergyDir, 'logs'),
114
- path.join(stigmergyDir, 'temp'),
115
- path.join(stigmergyDir, '.tmp'),
116
- ];
117
-
118
- for (const cachePath of cachePaths) {
119
- if (fs.existsSync(cachePath)) {
120
- await this.cleanDirectory(cachePath);
121
- }
122
- }
123
-
124
- console.log('ļæ½?Stigmergy cache cleaning completed');
125
- }
126
-
127
- /**
128
- * Clean a specific Stigmergy directory
129
- */
130
- async cleanStigmergyDirectory(dirPath, type) {
131
- console.log(` šŸ“‚ Cleaning ${type} directory...`);
132
-
133
- const files = await this.scanDirectory(dirPath);
134
- const recentFiles = this.filterRecentFiles(files);
135
-
136
- if (recentFiles.length === 0) {
137
- console.log(` ā„¹ļø No recent files to clean in ${type} directory`);
138
- return;
139
- }
140
-
141
- console.log(` šŸ“‹ Found ${recentFiles.length} files to clean`);
142
-
143
- if (this.options.dryRun) {
144
- this.logFiles(recentFiles, ' šŸ” ');
145
- return;
146
- }
147
-
148
- const removed = await this.batchRemoveFiles(recentFiles);
149
- console.log(` ļæ½?Removed ${removed} files from ${type} directory`);
150
- }
151
-
152
- /**
153
- * Clean NPX cache of Stigmergy entries
154
- */
155
- async cleanNPXCache() {
156
- console.log('šŸ“¦ Cleaning NPX cache...');
157
-
158
- const npxCacheDirs = await this.findNPXCacheDirectories();
159
-
160
- if (npxCacheDirs.length === 0) {
161
- console.log(' ā„¹ļø No Stigmergy entries in NPX cache');
162
- return;
163
- }
164
-
165
- console.log(` šŸ“¦ Found ${npxCacheDirs.length} Stigmergy cache entries`);
166
-
167
- if (this.options.dryRun) {
168
- this.logFiles(npxCacheDirs, ' šŸ” ');
169
- return;
170
- }
171
-
172
- let removed = 0;
173
- const failed = [];
174
-
175
- for (const cacheDir of npxCacheDirs) {
176
- try {
177
- const size = await this.getDirectorySize(cacheDir);
178
- await this.removeDirectory(cacheDir);
179
- this.results.bytesFreed += size;
180
- removed++;
181
- } catch (error) {
182
- failed.push(cacheDir);
183
- this.results.errors.push(`NPX cache ${cacheDir}: ${error.message}`);
184
- }
185
- }
186
-
187
- console.log(` ļæ½?Removed ${removed} NPX cache entries`);
188
- if (failed.length > 0) {
189
- console.log(` āš ļø Failed to remove ${failed.length} entries`);
190
- }
191
- }
192
-
193
- /**
194
- * Clean NPM cache
195
- */
196
- async cleanNPMCache() {
197
- console.log('šŸ“¦ Cleaning NPM cache...');
198
-
199
- try {
200
- // Use npm cache clean command
201
- if (this.options.dryRun) {
202
- console.log(' šŸ” Would run: npm cache clean --force');
203
- return;
204
- }
205
-
206
- const result = spawnSync('npm', ['cache', 'clean', '--force'], {
207
- encoding: 'utf8',
208
- shell: true,
209
- stdio: this.options.verbose ? 'inherit' : 'pipe',
210
- });
211
-
212
- if (result.status === 0) {
213
- console.log(' ļæ½?NPM cache cleaned successfully');
214
- } else {
215
- console.log(' āš ļø NPM cache clean failed, trying manual cleanup');
216
- await this.manualNPMCacheClean();
217
- }
218
- } catch (error) {
219
- console.error(` ļæ½?Failed to clean NPM cache: ${error.message}`);
220
- this.results.errors.push(`NPM cache: ${error.message}`);
221
- }
222
- }
223
-
224
- /**
225
- * Manual NPM cache cleaning fallback
226
- */
227
- async manualNPMCacheClean() {
228
- const npmCacheDirs = [
229
- path.join(this.homeDir, '.npm', '_cacache'),
230
- path.join(this.homeDir, 'AppData', 'Local', 'npm-cache', '_cacache'),
231
- ];
232
-
233
- for (const cacheDir of npmCacheDirs) {
234
- if (fs.existsSync(cacheDir)) {
235
- console.log(` 🧹 Manual cleanup of ${cacheDir}`);
236
- await this.cleanDirectory(cacheDir);
237
- }
238
- }
239
- }
240
-
241
- /**
242
- * Clean CLI configurations
243
- */
244
- async cleanCLIConfigurations() {
245
- console.log('āš™ļø Cleaning CLI configurations...');
246
-
247
- const supportedCLIs = [
248
- 'claude',
249
- 'gemini',
250
- 'qwen',
251
- 'iflow',
252
- 'qodercli',
253
- 'codebuddy',
254
- 'codex',
255
- 'copilot',
256
- 'qwencode',
257
- ];
258
-
259
- let totalCleaned = 0;
260
-
261
- for (const cli of supportedCLIs) {
262
- const cliConfig = path.join(this.homeDir, `.${cli}`);
263
-
264
- if (!fs.existsSync(cliConfig)) {
265
- continue;
266
- }
267
-
268
- const stigmergyFiles = await this.findStigmergyFiles(cliConfig);
269
-
270
- if (stigmergyFiles.length === 0) {
271
- continue;
272
- }
273
-
274
- console.log(` šŸ“‚ ${cli}: ${stigmergyFiles.length} Stigmergy files`);
275
-
276
- if (this.options.dryRun) {
277
- this.logFiles(stigmergyFiles, ' šŸ” ');
278
- continue;
279
- }
280
-
281
- const removed = await this.batchRemoveFiles(stigmergyFiles);
282
- totalCleaned += removed;
283
-
284
- if (removed > 0) {
285
- console.log(` ļæ½?Cleaned ${removed} files from ${cli}`);
286
- }
287
- }
288
-
289
- if (totalCleaned > 0) {
290
- console.log(` ļæ½?Cleaned ${totalCleaned} CLI configuration files`);
291
- }
292
- }
293
-
294
- /**
295
- * Clean temporary files
296
- */
297
- async cleanTemporaryFiles() {
298
- console.log('šŸ—‘ļæ½? Cleaning temporary files...');
299
-
300
- const tempDirs = [
301
- os.tmpdir(),
302
- path.join(this.homeDir, 'AppData', 'Local', 'Temp'),
303
- path.join(this.homeDir, 'AppData', 'Local', 'npm-cache', '_tmp'),
304
- ];
305
-
306
- let totalRemoved = 0;
307
-
308
- for (const tempDir of tempDirs) {
309
- if (!fs.existsSync(tempDir)) {
310
- continue;
311
- }
312
-
313
- const tempFiles = await this.findStigmergyTempFiles(tempDir);
314
-
315
- if (tempFiles.length === 0) {
316
- continue;
317
- }
318
-
319
- console.log(
320
- ` šŸ“‚ ${path.basename(tempDir)}: ${tempFiles.length} temporary files`,
321
- );
322
-
323
- if (this.options.dryRun) {
324
- this.logFiles(tempFiles.slice(0, 5), ' šŸ” ');
325
- if (tempFiles.length > 5) {
326
- console.log(` ... and ${tempFiles.length - 5} more`);
327
- }
328
- continue;
329
- }
330
-
331
- const removed = await this.batchRemoveFiles(tempFiles);
332
- totalRemoved += removed;
333
-
334
- if (removed > 0) {
335
- console.log(
336
- ` ļæ½?Removed ${removed} files from ${path.basename(tempDir)}`,
337
- );
338
- }
339
- }
340
-
341
- if (totalRemoved > 0) {
342
- console.log(` ļæ½?Removed ${totalRemoved} temporary files`);
343
- }
344
- }
345
-
346
- /**
347
- * Selective cleaning with patterns
348
- */
349
- async selectiveClean(targetDirectory, options = {}) {
350
- const {
351
- preservePatterns = [],
352
- removePatterns = [],
353
- preserveRecent = this.options.preserveRecent,
354
- } = options;
355
-
356
- console.log(`šŸŽÆ Selective cleaning: ${targetDirectory}`);
357
-
358
- if (!fs.existsSync(targetDirectory)) {
359
- console.log(' ā„¹ļø Directory not found');
360
- return;
361
- }
362
-
363
- const allFiles = await this.scanDirectory(targetDirectory);
364
- const filesToRemove = [];
365
-
366
- for (const file of allFiles) {
367
- // Check preserve patterns
368
- const shouldPreserve =
369
- preservePatterns.some((pattern) => this.matchPattern(file, pattern)) ||
370
- this.isRecentFile(file, preserveRecent);
371
-
372
- // Check remove patterns
373
- const shouldRemove = removePatterns.some((pattern) =>
374
- this.matchPattern(file, pattern),
375
- );
376
-
377
- if (shouldRemove && !shouldPreserve) {
378
- filesToRemove.push(file);
379
- }
380
- }
381
-
382
- console.log(` šŸ“‹ Found ${filesToRemove.length} files to remove`);
383
-
384
- if (this.options.dryRun) {
385
- this.logFiles(filesToRemove, ' šŸ” ');
386
- return;
387
- }
388
-
389
- const removed = await this.batchRemoveFiles(filesToRemove);
390
- console.log(` ļæ½?Selectively removed ${removed} files`);
391
- }
392
-
393
- /**
394
- * Performance-optimized cleaning
395
- */
396
- async cleanWithPerformance(targetDirectory, options = {}) {
397
- const {
398
- batchSize = this.options.batchSize,
399
- parallel = this.options.parallel,
400
- maxConcurrency = 4,
401
- } = options;
402
-
403
- console.log(`ļæ½?Performance cleaning: ${targetDirectory}`);
404
-
405
- const files = await this.scanDirectory(targetDirectory);
406
- const recentFiles = this.filterRecentFiles(files);
407
-
408
- console.log(
409
- ` šŸ“Š Processing ${recentFiles.length} files in batches of ${batchSize}`,
410
- );
411
-
412
- if (this.options.dryRun) {
413
- console.log(
414
- ` šŸ” Would process in ${Math.ceil(recentFiles.length / batchSize)} batches`,
415
- );
416
- return;
417
- }
418
-
419
- let removed = 0;
420
- const batches = this.createBatches(recentFiles, batchSize);
421
-
422
- if (parallel && batches.length > 1) {
423
- removed = await this.parallelRemoveBatches(batches, maxConcurrency);
424
- } else {
425
- for (const batch of batches) {
426
- const batchRemoved = await this.batchRemoveFiles(batch);
427
- removed += batchRemoved;
428
- }
429
- }
430
-
431
- console.log(` ļæ½?Performance cleaned ${removed} files`);
432
- return removed;
433
- }
434
-
435
- /**
436
- * Helper methods
437
- */
438
- async scanDirectory(dirPath, files = []) {
439
- try {
440
- const items = fs.readdirSync(dirPath, { withFileTypes: true });
441
-
442
- for (const item of items) {
443
- const fullPath = path.join(dirPath, item.name);
444
-
445
- if (item.isDirectory()) {
446
- await this.scanDirectory(fullPath, files);
447
- files.push(fullPath);
448
- } else {
449
- files.push(fullPath);
450
- }
451
- }
452
- } catch (error) {
453
- this.results.errors.push(`Scan error ${dirPath}: ${error.message}`);
454
- }
455
-
456
- return files;
457
- }
458
-
459
- async batchRemoveFiles(files) {
460
- let removed = 0;
461
-
462
- for (const file of files) {
463
- try {
464
- const stat = fs.statSync(file);
465
-
466
- if (this.removeFile(file)) {
467
- removed++;
468
- this.results.bytesFreed += stat.size;
469
- }
470
- } catch (error) {
471
- this.results.errors.push(`Remove error ${file}: ${error.message}`);
472
- }
473
- }
474
-
475
- this.results.filesRemoved += removed;
476
- return removed;
477
- }
478
-
479
- removeFile(filePath) {
480
- try {
481
- if (!fs.existsSync(filePath)) {
482
- return false;
483
- }
484
-
485
- const stat = fs.statSync(filePath);
486
-
487
- if (stat.isDirectory()) {
488
- fs.rmSync(filePath, { recursive: true, force: true });
489
- this.results.directoriesRemoved++;
490
- } else {
491
- fs.unlinkSync(filePath);
492
- }
493
-
494
- if (this.options.verbose) {
495
- console.log(` Removed: ${path.basename(filePath)}`);
496
- }
497
-
498
- return true;
499
- } catch (error) {
500
- if (!this.options.force) {
501
- throw error;
502
- }
503
- this.results.skipped.push(`${filePath}: ${error.message}`);
504
- return false;
505
- }
506
- }
507
-
508
- async removeDirectory(dirPath) {
509
- try {
510
- if (fs.existsSync(dirPath)) {
511
- const size = await this.getDirectorySize(dirPath);
512
- fs.rmSync(dirPath, { recursive: true, force: true });
513
- this.results.bytesFreed += size;
514
- this.results.directoriesRemoved++;
515
- return true;
516
- }
517
- return false;
518
- } catch (error) {
519
- if (!this.options.force) {
520
- throw error;
521
- }
522
- this.results.skipped.push(`Directory: ${dirPath} (${error.message})`);
523
- return false;
524
- }
525
- }
526
-
527
- async getDirectorySize(dirPath) {
528
- let totalSize = 0;
529
-
530
- try {
531
- const files = await this.scanDirectory(dirPath);
532
-
533
- for (const file of files) {
534
- try {
535
- const stat = fs.statSync(file);
536
- totalSize += stat.size;
537
- } catch (error) {
538
- // Skip files we can't stat
539
- }
540
- }
541
- } catch (error) {
542
- // Return 0 for directories we can't scan
543
- }
544
-
545
- return totalSize;
546
- }
547
-
548
- filterRecentFiles(files) {
549
- return files.filter(
550
- (file) => !this.isRecentFile(file, this.options.preserveRecent),
551
- );
552
- }
553
-
554
- isRecentFile(filePath, maxAge) {
555
- try {
556
- const stat = fs.statSync(filePath);
557
- const age = Date.now() - stat.mtime.getTime();
558
- return age < maxAge;
559
- } catch (error) {
560
- return false;
561
- }
562
- }
563
-
564
- async findStigmergyFiles(dirPath) {
565
- const stigmergyFiles = [];
566
-
567
- try {
568
- const files = fs.readdirSync(dirPath, { withFileTypes: true });
569
-
570
- for (const file of files) {
571
- const fullPath = path.join(dirPath, file.name);
572
-
573
- if (file.isDirectory()) {
574
- stigmergyFiles.push(...(await this.findStigmergyFiles(fullPath)));
575
- } else if (this.isStigmergyFile(file.name)) {
576
- stigmergyFiles.push(fullPath);
577
- }
578
- }
579
- } catch (error) {
580
- // Skip directories we can't read
581
- }
582
-
583
- return stigmergyFiles;
584
- }
585
-
586
- isStigmergyFile(fileName) {
587
- const stigmergyPatterns = [
588
- 'stigmergy',
589
- 'cross-cli',
590
- 'hook',
591
- 'integration',
592
- 'cache',
593
- '.tmp',
594
- 'temp',
595
- ];
596
-
597
- const lowerFileName = fileName.toLowerCase();
598
- return stigmergyPatterns.some((pattern) =>
599
- lowerFileName.includes(pattern.toLowerCase()),
600
- );
601
- }
602
-
603
- async findNPXCacheDirectories() {
604
- const cacheDirs = [];
605
- const possibleNPXBases = [
606
- path.join(this.homeDir, 'AppData', 'Local', 'npm-cache', '_npx'),
607
- path.join(this.homeDir, '.npm', '_npx'),
608
- path.join(os.tmpdir(), 'npm-cache', '_npx'),
609
- ];
610
-
611
- for (const npxCacheBase of possibleNPXBases) {
612
- if (!fs.existsSync(npxCacheBase)) {
613
- continue;
614
- }
615
-
616
- try {
617
- const entries = fs.readdirSync(npxCacheBase);
618
-
619
- for (const entry of entries) {
620
- const entryPath = path.join(npxCacheBase, entry);
621
- const stigmergyPath = path.join(
622
- entryPath,
623
- 'node_modules',
624
- 'stigmergy',
625
- );
626
-
627
- if (fs.existsSync(stigmergyPath)) {
628
- cacheDirs.push(entryPath);
629
- }
630
- }
631
- } catch (error) {
632
- this.results.errors.push(`NPX scan error: ${error.message}`);
633
- }
634
- }
635
-
636
- return cacheDirs;
637
- }
638
-
639
- async findStigmergyTempFiles(tempDir) {
640
- const tempFiles = [];
641
-
642
- try {
643
- const files = fs.readdirSync(tempDir, { withFileTypes: true });
644
-
645
- for (const file of files) {
646
- if (
647
- this.isStigmergyFile(file.name) ||
648
- file.name.startsWith('stigmergy-') ||
649
- file.name.includes('stigmergy')
650
- ) {
651
- const fullPath = path.join(tempDir, file.name);
652
- tempFiles.push(fullPath);
653
- }
654
- }
655
- } catch (error) {
656
- // Skip temp directories we can't read
657
- }
658
-
659
- return tempFiles;
660
- }
661
-
662
- async cleanDirectory(dirPath) {
663
- try {
664
- if (!fs.existsSync(dirPath)) {
665
- return;
666
- }
667
-
668
- const files = await this.scanDirectory(dirPath);
669
- const removed = await this.batchRemoveFiles(files);
670
-
671
- console.log(
672
- ` 🧹 Cleaned ${removed} files from ${path.basename(dirPath)}`,
673
- );
674
- } catch (error) {
675
- console.error(` ļæ½?Failed to clean ${dirPath}: ${error.message}`);
676
- this.results.errors.push(`Clean error ${dirPath}: ${error.message}`);
677
- }
678
- }
679
-
680
- matchPattern(filePath, pattern) {
681
- const fileName = path.basename(filePath);
682
-
683
- // Simple glob pattern matching
684
- const regexPattern = pattern.replace(/\*/g, '.*').replace(/\?/g, '.');
685
-
686
- const regex = new RegExp(regexPattern, 'i');
687
- return regex.test(fileName);
688
- }
689
-
690
- createBatches(items, batchSize) {
691
- const batches = [];
692
- for (let i = 0; i < items.length; i += batchSize) {
693
- batches.push(items.slice(i, i + batchSize));
694
- }
695
- return batches;
696
- }
697
-
698
- async parallelRemoveBatches(batches, maxConcurrency) {
699
- let totalRemoved = 0;
700
- const executing = [];
701
-
702
- for (const batch of batches) {
703
- const promise = this.batchRemoveFiles(batch);
704
- executing.push(promise);
705
-
706
- if (executing.length >= maxConcurrency) {
707
- await Promise.race(executing);
708
- executing.splice(0, 1);
709
- }
710
- }
711
-
712
- await Promise.all(executing);
713
- return totalRemoved;
714
- }
715
-
716
- formatBytes(bytes) {
717
- const sizes = ['Bytes', 'KB', 'MB', 'GB'];
718
- if (bytes === 0) return '0 Bytes';
719
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
720
- return Math.round((bytes / Math.pow(1024, i)) * 100) / 100 + ' ' + sizes[i];
721
- }
722
-
723
- logFiles(files, prefix = '') {
724
- files.slice(0, 10).forEach((file) => {
725
- console.log(`${prefix}${path.basename(file)}`);
726
- });
727
-
728
- if (files.length > 10) {
729
- console.log(`${prefix}... and ${files.length - 10} more`);
730
- }
731
- }
732
-
733
- printSummary() {
734
- console.log('\nšŸ“Š CACHE CLEANING SUMMARY:');
735
- console.log('='.repeat(50));
736
-
737
- if (this.options.dryRun) {
738
- console.log('šŸ” DRY RUN MODE - No files were actually deleted');
739
- } else {
740
- console.log(`šŸ“ Directories removed: ${this.results.directoriesRemoved}`);
741
- console.log(`šŸ“„ Files removed: ${this.results.filesRemoved}`);
742
- console.log(
743
- `šŸ’¾ Space freed: ${this.formatBytes(this.results.bytesFreed)}`,
744
- );
745
- }
746
-
747
- if (this.results.skipped.length > 0) {
748
- console.log(`ā­ļø Items skipped: ${this.results.skipped.length}`);
749
- if (this.options.verbose) {
750
- this.results.skipped.forEach((item) => {
751
- console.log(` ${item}`);
752
- });
753
- }
754
- }
755
-
756
- if (this.results.errors.length > 0) {
757
- console.log(`ļæ½?Errors: ${this.results.errors.length}`);
758
- this.results.errors.forEach((error) => {
759
- console.log(` ${error}`);
760
- });
761
- }
762
-
763
- console.log('\nļæ½?Cache cleaning completed!');
764
- }
765
- }
766
-
767
- module.exports = CacheCleaner;
1
+ /**
2
+ * Comprehensive Cache Cleaner for Stigmergy
3
+ *
4
+ * Intelligent cache cleaning with selective removal, performance optimization,
5
+ * and error recovery capabilities.
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const os = require('os');
11
+ const { spawnSync } = require('child_process');
12
+
13
+ class CacheCleaner {
14
+ constructor(options = {}) {
15
+ this.options = {
16
+ dryRun: options.dryRun || false,
17
+ force: options.force || false,
18
+ verbose: options.verbose || false,
19
+ preserveRecent: options.preserveRecent || 24 * 60 * 60 * 1000, // 24 hours
20
+ batchSize: options.batchSize || 50,
21
+ parallel: options.parallel || true,
22
+ ...options,
23
+ };
24
+
25
+ this.homeDir = os.homedir();
26
+ this.results = {
27
+ filesRemoved: 0,
28
+ directoriesRemoved: 0,
29
+ bytesFreed: 0,
30
+ errors: [],
31
+ skipped: [],
32
+ };
33
+ }
34
+
35
+ /**
36
+ * Clean all caches comprehensively
37
+ */
38
+ async cleanAllCaches(options = {}) {
39
+ const config = {
40
+ cleanStigmergy: true,
41
+ cleanNPX: true,
42
+ cleanNPM: true,
43
+ cleanCLI: true,
44
+ cleanTemp: true,
45
+ ...options,
46
+ };
47
+
48
+ console.log('🧹 Starting Comprehensive Cache Cleaning...\n');
49
+
50
+ if (this.options.dryRun) {
51
+ console.log('šŸ” DRY RUN MODE - No files will be deleted\n');
52
+ }
53
+
54
+ try {
55
+ // 1. Clean Stigmergy cache
56
+ if (config.cleanStigmergy) {
57
+ await this.cleanStigmergyCache();
58
+ }
59
+
60
+ // 2. Clean NPX cache
61
+ if (config.cleanNPX) {
62
+ await this.cleanNPXCache();
63
+ }
64
+
65
+ // 3. Clean NPM cache
66
+ if (config.cleanNPM) {
67
+ await this.cleanNPMCache();
68
+ }
69
+
70
+ // 4. Clean CLI configurations
71
+ if (config.cleanCLI) {
72
+ await this.cleanCLIConfigurations();
73
+ }
74
+
75
+ // 5. Clean temporary files
76
+ if (config.cleanTemp) {
77
+ await this.cleanTemporaryFiles();
78
+ }
79
+
80
+ // 6. Print summary
81
+ this.printSummary();
82
+
83
+ return this.results;
84
+ } catch (error) {
85
+ console.error('ļæ½?Cache cleaning failed:', error.message);
86
+ this.results.errors.push(error.message);
87
+ return this.results;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Clean Stigmergy cache and temporary files
93
+ */
94
+ async cleanStigmergyCache() {
95
+ console.log('šŸ“ Cleaning Stigmergy cache...');
96
+
97
+ const stigmergyDir = path.join(this.homeDir, '.stigmergy');
98
+ const testDir = path.join(this.homeDir, '.stigmergy-test');
99
+
100
+ // Clean main cache directory
101
+ if (fs.existsSync(stigmergyDir)) {
102
+ await this.cleanStigmergyDirectory(stigmergyDir, 'main');
103
+ }
104
+
105
+ // Clean test directory
106
+ if (fs.existsSync(testDir)) {
107
+ await this.cleanStigmergyDirectory(testDir, 'test');
108
+ }
109
+
110
+ // Clean cache subdirectories specifically
111
+ const cachePaths = [
112
+ path.join(stigmergyDir, 'cache'),
113
+ path.join(stigmergyDir, 'logs'),
114
+ path.join(stigmergyDir, 'temp'),
115
+ path.join(stigmergyDir, '.tmp'),
116
+ ];
117
+
118
+ for (const cachePath of cachePaths) {
119
+ if (fs.existsSync(cachePath)) {
120
+ await this.cleanDirectory(cachePath);
121
+ }
122
+ }
123
+
124
+ console.log('ļæ½?Stigmergy cache cleaning completed');
125
+ }
126
+
127
+ /**
128
+ * Clean a specific Stigmergy directory
129
+ */
130
+ async cleanStigmergyDirectory(dirPath, type) {
131
+ console.log(` šŸ“‚ Cleaning ${type} directory...`);
132
+
133
+ const files = await this.scanDirectory(dirPath);
134
+ const recentFiles = this.filterRecentFiles(files);
135
+
136
+ if (recentFiles.length === 0) {
137
+ console.log(` ā„¹ļø No recent files to clean in ${type} directory`);
138
+ return;
139
+ }
140
+
141
+ console.log(` šŸ“‹ Found ${recentFiles.length} files to clean`);
142
+
143
+ if (this.options.dryRun) {
144
+ this.logFiles(recentFiles, ' šŸ” ');
145
+ return;
146
+ }
147
+
148
+ const removed = await this.batchRemoveFiles(recentFiles);
149
+ console.log(` ļæ½?Removed ${removed} files from ${type} directory`);
150
+ }
151
+
152
+ /**
153
+ * Clean NPX cache of Stigmergy entries
154
+ */
155
+ async cleanNPXCache() {
156
+ console.log('šŸ“¦ Cleaning NPX cache...');
157
+
158
+ const npxCacheDirs = await this.findNPXCacheDirectories();
159
+
160
+ if (npxCacheDirs.length === 0) {
161
+ console.log(' ā„¹ļø No Stigmergy entries in NPX cache');
162
+ return;
163
+ }
164
+
165
+ console.log(` šŸ“¦ Found ${npxCacheDirs.length} Stigmergy cache entries`);
166
+
167
+ if (this.options.dryRun) {
168
+ this.logFiles(npxCacheDirs, ' šŸ” ');
169
+ return;
170
+ }
171
+
172
+ let removed = 0;
173
+ const failed = [];
174
+
175
+ for (const cacheDir of npxCacheDirs) {
176
+ try {
177
+ const size = await this.getDirectorySize(cacheDir);
178
+ await this.removeDirectory(cacheDir);
179
+ this.results.bytesFreed += size;
180
+ removed++;
181
+ } catch (error) {
182
+ failed.push(cacheDir);
183
+ this.results.errors.push(`NPX cache ${cacheDir}: ${error.message}`);
184
+ }
185
+ }
186
+
187
+ console.log(` ļæ½?Removed ${removed} NPX cache entries`);
188
+ if (failed.length > 0) {
189
+ console.log(` āš ļø Failed to remove ${failed.length} entries`);
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Clean NPM cache
195
+ */
196
+ async cleanNPMCache() {
197
+ console.log('šŸ“¦ Cleaning NPM cache...');
198
+
199
+ try {
200
+ // Use npm cache clean command
201
+ if (this.options.dryRun) {
202
+ console.log(' šŸ” Would run: npm cache clean --force');
203
+ return;
204
+ }
205
+
206
+ const result = spawnSync('npm', ['cache', 'clean', '--force'], {
207
+ encoding: 'utf8',
208
+ shell: true,
209
+ stdio: this.options.verbose ? 'inherit' : 'pipe',
210
+ });
211
+
212
+ if (result.status === 0) {
213
+ console.log(' ļæ½?NPM cache cleaned successfully');
214
+ } else {
215
+ console.log(' āš ļø NPM cache clean failed, trying manual cleanup');
216
+ await this.manualNPMCacheClean();
217
+ }
218
+ } catch (error) {
219
+ console.error(` ļæ½?Failed to clean NPM cache: ${error.message}`);
220
+ this.results.errors.push(`NPM cache: ${error.message}`);
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Manual NPM cache cleaning fallback
226
+ */
227
+ async manualNPMCacheClean() {
228
+ const npmCacheDirs = [
229
+ path.join(this.homeDir, '.npm', '_cacache'),
230
+ path.join(this.homeDir, 'AppData', 'Local', 'npm-cache', '_cacache'),
231
+ ];
232
+
233
+ for (const cacheDir of npmCacheDirs) {
234
+ if (fs.existsSync(cacheDir)) {
235
+ console.log(` 🧹 Manual cleanup of ${cacheDir}`);
236
+ await this.cleanDirectory(cacheDir);
237
+ }
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Clean CLI configurations
243
+ */
244
+ async cleanCLIConfigurations() {
245
+ console.log('āš™ļø Cleaning CLI configurations...');
246
+
247
+ const supportedCLIs = [
248
+ 'claude',
249
+ 'gemini',
250
+ 'qwen',
251
+ 'iflow',
252
+ 'qodercli',
253
+ 'codebuddy',
254
+ 'codex',
255
+ 'copilot',
256
+ 'qwencode',
257
+ ];
258
+
259
+ let totalCleaned = 0;
260
+
261
+ for (const cli of supportedCLIs) {
262
+ const cliConfig = path.join(this.homeDir, `.${cli}`);
263
+
264
+ if (!fs.existsSync(cliConfig)) {
265
+ continue;
266
+ }
267
+
268
+ const stigmergyFiles = await this.findStigmergyFiles(cliConfig);
269
+
270
+ if (stigmergyFiles.length === 0) {
271
+ continue;
272
+ }
273
+
274
+ console.log(` šŸ“‚ ${cli}: ${stigmergyFiles.length} Stigmergy files`);
275
+
276
+ if (this.options.dryRun) {
277
+ this.logFiles(stigmergyFiles, ' šŸ” ');
278
+ continue;
279
+ }
280
+
281
+ const removed = await this.batchRemoveFiles(stigmergyFiles);
282
+ totalCleaned += removed;
283
+
284
+ if (removed > 0) {
285
+ console.log(` ļæ½?Cleaned ${removed} files from ${cli}`);
286
+ }
287
+ }
288
+
289
+ if (totalCleaned > 0) {
290
+ console.log(` ļæ½?Cleaned ${totalCleaned} CLI configuration files`);
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Clean temporary files
296
+ */
297
+ async cleanTemporaryFiles() {
298
+ console.log('šŸ—‘ļæ½? Cleaning temporary files...');
299
+
300
+ const tempDirs = [
301
+ os.tmpdir(),
302
+ path.join(this.homeDir, 'AppData', 'Local', 'Temp'),
303
+ path.join(this.homeDir, 'AppData', 'Local', 'npm-cache', '_tmp'),
304
+ ];
305
+
306
+ let totalRemoved = 0;
307
+
308
+ for (const tempDir of tempDirs) {
309
+ if (!fs.existsSync(tempDir)) {
310
+ continue;
311
+ }
312
+
313
+ const tempFiles = await this.findStigmergyTempFiles(tempDir);
314
+
315
+ if (tempFiles.length === 0) {
316
+ continue;
317
+ }
318
+
319
+ console.log(
320
+ ` šŸ“‚ ${path.basename(tempDir)}: ${tempFiles.length} temporary files`,
321
+ );
322
+
323
+ if (this.options.dryRun) {
324
+ this.logFiles(tempFiles.slice(0, 5), ' šŸ” ');
325
+ if (tempFiles.length > 5) {
326
+ console.log(` ... and ${tempFiles.length - 5} more`);
327
+ }
328
+ continue;
329
+ }
330
+
331
+ const removed = await this.batchRemoveFiles(tempFiles);
332
+ totalRemoved += removed;
333
+
334
+ if (removed > 0) {
335
+ console.log(
336
+ ` ļæ½?Removed ${removed} files from ${path.basename(tempDir)}`,
337
+ );
338
+ }
339
+ }
340
+
341
+ if (totalRemoved > 0) {
342
+ console.log(` ļæ½?Removed ${totalRemoved} temporary files`);
343
+ }
344
+ }
345
+
346
+ /**
347
+ * Selective cleaning with patterns
348
+ */
349
+ async selectiveClean(targetDirectory, options = {}) {
350
+ const {
351
+ preservePatterns = [],
352
+ removePatterns = [],
353
+ preserveRecent = this.options.preserveRecent,
354
+ } = options;
355
+
356
+ console.log(`šŸŽÆ Selective cleaning: ${targetDirectory}`);
357
+
358
+ if (!fs.existsSync(targetDirectory)) {
359
+ console.log(' ā„¹ļø Directory not found');
360
+ return;
361
+ }
362
+
363
+ const allFiles = await this.scanDirectory(targetDirectory);
364
+ const filesToRemove = [];
365
+
366
+ for (const file of allFiles) {
367
+ // Check preserve patterns
368
+ const shouldPreserve =
369
+ preservePatterns.some((pattern) => this.matchPattern(file, pattern)) ||
370
+ this.isRecentFile(file, preserveRecent);
371
+
372
+ // Check remove patterns
373
+ const shouldRemove = removePatterns.some((pattern) =>
374
+ this.matchPattern(file, pattern),
375
+ );
376
+
377
+ if (shouldRemove && !shouldPreserve) {
378
+ filesToRemove.push(file);
379
+ }
380
+ }
381
+
382
+ console.log(` šŸ“‹ Found ${filesToRemove.length} files to remove`);
383
+
384
+ if (this.options.dryRun) {
385
+ this.logFiles(filesToRemove, ' šŸ” ');
386
+ return;
387
+ }
388
+
389
+ const removed = await this.batchRemoveFiles(filesToRemove);
390
+ console.log(` ļæ½?Selectively removed ${removed} files`);
391
+ }
392
+
393
+ /**
394
+ * Performance-optimized cleaning
395
+ */
396
+ async cleanWithPerformance(targetDirectory, options = {}) {
397
+ const {
398
+ batchSize = this.options.batchSize,
399
+ parallel = this.options.parallel,
400
+ maxConcurrency = 4,
401
+ } = options;
402
+
403
+ console.log(`ļæ½?Performance cleaning: ${targetDirectory}`);
404
+
405
+ const files = await this.scanDirectory(targetDirectory);
406
+ const recentFiles = this.filterRecentFiles(files);
407
+
408
+ console.log(
409
+ ` šŸ“Š Processing ${recentFiles.length} files in batches of ${batchSize}`,
410
+ );
411
+
412
+ if (this.options.dryRun) {
413
+ console.log(
414
+ ` šŸ” Would process in ${Math.ceil(recentFiles.length / batchSize)} batches`,
415
+ );
416
+ return;
417
+ }
418
+
419
+ let removed = 0;
420
+ const batches = this.createBatches(recentFiles, batchSize);
421
+
422
+ if (parallel && batches.length > 1) {
423
+ removed = await this.parallelRemoveBatches(batches, maxConcurrency);
424
+ } else {
425
+ for (const batch of batches) {
426
+ const batchRemoved = await this.batchRemoveFiles(batch);
427
+ removed += batchRemoved;
428
+ }
429
+ }
430
+
431
+ console.log(` ļæ½?Performance cleaned ${removed} files`);
432
+ return removed;
433
+ }
434
+
435
+ /**
436
+ * Helper methods
437
+ */
438
+ async scanDirectory(dirPath, files = []) {
439
+ try {
440
+ const items = fs.readdirSync(dirPath, { withFileTypes: true });
441
+
442
+ for (const item of items) {
443
+ const fullPath = path.join(dirPath, item.name);
444
+
445
+ if (item.isDirectory()) {
446
+ await this.scanDirectory(fullPath, files);
447
+ files.push(fullPath);
448
+ } else {
449
+ files.push(fullPath);
450
+ }
451
+ }
452
+ } catch (error) {
453
+ this.results.errors.push(`Scan error ${dirPath}: ${error.message}`);
454
+ }
455
+
456
+ return files;
457
+ }
458
+
459
+ async batchRemoveFiles(files) {
460
+ let removed = 0;
461
+
462
+ for (const file of files) {
463
+ try {
464
+ const stat = fs.statSync(file);
465
+
466
+ if (this.removeFile(file)) {
467
+ removed++;
468
+ this.results.bytesFreed += stat.size;
469
+ }
470
+ } catch (error) {
471
+ this.results.errors.push(`Remove error ${file}: ${error.message}`);
472
+ }
473
+ }
474
+
475
+ this.results.filesRemoved += removed;
476
+ return removed;
477
+ }
478
+
479
+ removeFile(filePath) {
480
+ try {
481
+ if (!fs.existsSync(filePath)) {
482
+ return false;
483
+ }
484
+
485
+ const stat = fs.statSync(filePath);
486
+
487
+ if (stat.isDirectory()) {
488
+ fs.rmSync(filePath, { recursive: true, force: true });
489
+ this.results.directoriesRemoved++;
490
+ } else {
491
+ fs.unlinkSync(filePath);
492
+ }
493
+
494
+ if (this.options.verbose) {
495
+ console.log(` Removed: ${path.basename(filePath)}`);
496
+ }
497
+
498
+ return true;
499
+ } catch (error) {
500
+ if (!this.options.force) {
501
+ throw error;
502
+ }
503
+ this.results.skipped.push(`${filePath}: ${error.message}`);
504
+ return false;
505
+ }
506
+ }
507
+
508
+ async removeDirectory(dirPath) {
509
+ try {
510
+ if (fs.existsSync(dirPath)) {
511
+ const size = await this.getDirectorySize(dirPath);
512
+ fs.rmSync(dirPath, { recursive: true, force: true });
513
+ this.results.bytesFreed += size;
514
+ this.results.directoriesRemoved++;
515
+ return true;
516
+ }
517
+ return false;
518
+ } catch (error) {
519
+ if (!this.options.force) {
520
+ throw error;
521
+ }
522
+ this.results.skipped.push(`Directory: ${dirPath} (${error.message})`);
523
+ return false;
524
+ }
525
+ }
526
+
527
+ async getDirectorySize(dirPath) {
528
+ let totalSize = 0;
529
+
530
+ try {
531
+ const files = await this.scanDirectory(dirPath);
532
+
533
+ for (const file of files) {
534
+ try {
535
+ const stat = fs.statSync(file);
536
+ totalSize += stat.size;
537
+ } catch (error) {
538
+ // Skip files we can't stat
539
+ }
540
+ }
541
+ } catch (error) {
542
+ // Return 0 for directories we can't scan
543
+ }
544
+
545
+ return totalSize;
546
+ }
547
+
548
+ filterRecentFiles(files) {
549
+ return files.filter(
550
+ (file) => !this.isRecentFile(file, this.options.preserveRecent),
551
+ );
552
+ }
553
+
554
+ isRecentFile(filePath, maxAge) {
555
+ try {
556
+ const stat = fs.statSync(filePath);
557
+ const age = Date.now() - stat.mtime.getTime();
558
+ return age < maxAge;
559
+ } catch (error) {
560
+ return false;
561
+ }
562
+ }
563
+
564
+ async findStigmergyFiles(dirPath) {
565
+ const stigmergyFiles = [];
566
+
567
+ try {
568
+ const files = fs.readdirSync(dirPath, { withFileTypes: true });
569
+
570
+ for (const file of files) {
571
+ const fullPath = path.join(dirPath, file.name);
572
+
573
+ if (file.isDirectory()) {
574
+ stigmergyFiles.push(...(await this.findStigmergyFiles(fullPath)));
575
+ } else if (this.isStigmergyFile(file.name)) {
576
+ stigmergyFiles.push(fullPath);
577
+ }
578
+ }
579
+ } catch (error) {
580
+ // Skip directories we can't read
581
+ }
582
+
583
+ return stigmergyFiles;
584
+ }
585
+
586
+ isStigmergyFile(fileName) {
587
+ const stigmergyPatterns = [
588
+ 'stigmergy',
589
+ 'cross-cli',
590
+ 'hook',
591
+ 'integration',
592
+ 'cache',
593
+ '.tmp',
594
+ 'temp',
595
+ ];
596
+
597
+ const lowerFileName = fileName.toLowerCase();
598
+ return stigmergyPatterns.some((pattern) =>
599
+ lowerFileName.includes(pattern.toLowerCase()),
600
+ );
601
+ }
602
+
603
+ async findNPXCacheDirectories() {
604
+ const cacheDirs = [];
605
+ const possibleNPXBases = [
606
+ path.join(this.homeDir, 'AppData', 'Local', 'npm-cache', '_npx'),
607
+ path.join(this.homeDir, '.npm', '_npx'),
608
+ path.join(os.tmpdir(), 'npm-cache', '_npx'),
609
+ ];
610
+
611
+ for (const npxCacheBase of possibleNPXBases) {
612
+ if (!fs.existsSync(npxCacheBase)) {
613
+ continue;
614
+ }
615
+
616
+ try {
617
+ const entries = fs.readdirSync(npxCacheBase);
618
+
619
+ for (const entry of entries) {
620
+ const entryPath = path.join(npxCacheBase, entry);
621
+ const stigmergyPath = path.join(
622
+ entryPath,
623
+ 'node_modules',
624
+ 'stigmergy',
625
+ );
626
+
627
+ if (fs.existsSync(stigmergyPath)) {
628
+ cacheDirs.push(entryPath);
629
+ }
630
+ }
631
+ } catch (error) {
632
+ this.results.errors.push(`NPX scan error: ${error.message}`);
633
+ }
634
+ }
635
+
636
+ return cacheDirs;
637
+ }
638
+
639
+ async findStigmergyTempFiles(tempDir) {
640
+ const tempFiles = [];
641
+
642
+ try {
643
+ const files = fs.readdirSync(tempDir, { withFileTypes: true });
644
+
645
+ for (const file of files) {
646
+ if (
647
+ this.isStigmergyFile(file.name) ||
648
+ file.name.startsWith('stigmergy-') ||
649
+ file.name.includes('stigmergy')
650
+ ) {
651
+ const fullPath = path.join(tempDir, file.name);
652
+ tempFiles.push(fullPath);
653
+ }
654
+ }
655
+ } catch (error) {
656
+ // Skip temp directories we can't read
657
+ }
658
+
659
+ return tempFiles;
660
+ }
661
+
662
+ async cleanDirectory(dirPath) {
663
+ try {
664
+ if (!fs.existsSync(dirPath)) {
665
+ return;
666
+ }
667
+
668
+ const files = await this.scanDirectory(dirPath);
669
+ const removed = await this.batchRemoveFiles(files);
670
+
671
+ console.log(
672
+ ` 🧹 Cleaned ${removed} files from ${path.basename(dirPath)}`,
673
+ );
674
+ } catch (error) {
675
+ console.error(` ļæ½?Failed to clean ${dirPath}: ${error.message}`);
676
+ this.results.errors.push(`Clean error ${dirPath}: ${error.message}`);
677
+ }
678
+ }
679
+
680
+ matchPattern(filePath, pattern) {
681
+ const fileName = path.basename(filePath);
682
+
683
+ // Simple glob pattern matching
684
+ const regexPattern = pattern.replace(/\*/g, '.*').replace(/\?/g, '.');
685
+
686
+ const regex = new RegExp(regexPattern, 'i');
687
+ return regex.test(fileName);
688
+ }
689
+
690
+ createBatches(items, batchSize) {
691
+ const batches = [];
692
+ for (let i = 0; i < items.length; i += batchSize) {
693
+ batches.push(items.slice(i, i + batchSize));
694
+ }
695
+ return batches;
696
+ }
697
+
698
+ async parallelRemoveBatches(batches, maxConcurrency) {
699
+ let totalRemoved = 0;
700
+ const executing = [];
701
+
702
+ for (const batch of batches) {
703
+ const promise = this.batchRemoveFiles(batch);
704
+ executing.push(promise);
705
+
706
+ if (executing.length >= maxConcurrency) {
707
+ await Promise.race(executing);
708
+ executing.splice(0, 1);
709
+ }
710
+ }
711
+
712
+ await Promise.all(executing);
713
+ return totalRemoved;
714
+ }
715
+
716
+ formatBytes(bytes) {
717
+ const sizes = ['Bytes', 'KB', 'MB', 'GB'];
718
+ if (bytes === 0) return '0 Bytes';
719
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
720
+ return Math.round((bytes / Math.pow(1024, i)) * 100) / 100 + ' ' + sizes[i];
721
+ }
722
+
723
+ logFiles(files, prefix = '') {
724
+ files.slice(0, 10).forEach((file) => {
725
+ console.log(`${prefix}${path.basename(file)}`);
726
+ });
727
+
728
+ if (files.length > 10) {
729
+ console.log(`${prefix}... and ${files.length - 10} more`);
730
+ }
731
+ }
732
+
733
+ printSummary() {
734
+ console.log('\nšŸ“Š CACHE CLEANING SUMMARY:');
735
+ console.log('='.repeat(50));
736
+
737
+ if (this.options.dryRun) {
738
+ console.log('šŸ” DRY RUN MODE - No files were actually deleted');
739
+ } else {
740
+ console.log(`šŸ“ Directories removed: ${this.results.directoriesRemoved}`);
741
+ console.log(`šŸ“„ Files removed: ${this.results.filesRemoved}`);
742
+ console.log(
743
+ `šŸ’¾ Space freed: ${this.formatBytes(this.results.bytesFreed)}`,
744
+ );
745
+ }
746
+
747
+ if (this.results.skipped.length > 0) {
748
+ console.log(`ā­ļø Items skipped: ${this.results.skipped.length}`);
749
+ if (this.options.verbose) {
750
+ this.results.skipped.forEach((item) => {
751
+ console.log(` ${item}`);
752
+ });
753
+ }
754
+ }
755
+
756
+ if (this.results.errors.length > 0) {
757
+ console.log(`ļæ½?Errors: ${this.results.errors.length}`);
758
+ this.results.errors.forEach((error) => {
759
+ console.log(` ${error}`);
760
+ });
761
+ }
762
+
763
+ console.log('\nļæ½?Cache cleaning completed!');
764
+ }
765
+ }
766
+
767
+ module.exports = CacheCleaner;