vacumify-mcp 1.1.0 → 1.2.0

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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Connect **Vacumify** directly to AI agent environments such as **Claude Code**, **Claude Desktop**, **Cursor**, **Windsurf**, and **Google Antigravity**.
4
4
 
5
- Runs completely standalone over `stdio` without opening the desktop GUI. If `Vacumify.exe` is not found locally, `npx -y vacumify-mcp` automatically downloads the official Windows x64 binary from GitHub Releases into `~/.vacumify/`.
5
+ Runs completely standalone in pure Node.js (zero dependencies, zero `.exe` downloads) over `stdio` on **Windows, macOS, and Linux** — no desktop GUI installation required.
6
6
 
7
7
  ---
8
8
 
@@ -1,98 +1,634 @@
1
1
  #!/usr/bin/env node
2
+ 'use strict';
2
3
 
3
- const { spawn, execSync } = require('child_process');
4
4
  const fs = require('fs');
5
5
  const path = require('path');
6
+ const readline = require('readline');
7
+ const scanner = require('../lib/scanner');
6
8
 
7
- function findVacumifyExecutable() {
8
- // 1. Explicit env variable
9
- if (process.env.VACUMIFY_PATH && fs.existsSync(process.env.VACUMIFY_PATH)) {
10
- return process.env.VACUMIFY_PATH;
11
- }
12
-
13
- // 2. Relative paths within the Vacumify repo
14
- const candidates = [
15
- path.resolve(__dirname, '../../StorageCleaner/StorageCleaner/bin/Release/net10.0-windows/win-x64/publish/Vacumify.exe'),
16
- path.resolve(__dirname, '../../StorageCleaner/StorageCleaner/bin/Release/net10.0-windows/win-x64/Vacumify.exe'),
17
- path.resolve(__dirname, '../../StorageCleaner/StorageCleaner/bin/Debug/net10.0-windows/Vacumify.exe'),
18
- path.resolve(process.cwd(), 'Vacumify.exe')
19
- ];
9
+ const SERVER_NAME = 'vacumify';
10
+ const SERVER_VERSION = '1.2.0';
11
+ const PROTOCOL_VERSION = '2024-11-05';
12
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
20
13
 
21
- for (const cand of candidates) {
22
- if (fs.existsSync(cand)) return cand;
14
+ const TOOLS = [
15
+ {
16
+ name: 'vacumify_scan',
17
+ description:
18
+ 'Scan a local folder to identify large files, duplicate file groups, forgotten files, and developer caches with Active/Dormant/Abandoned project context. Read-only operation.',
19
+ inputSchema: {
20
+ type: 'object',
21
+ properties: {
22
+ path: {
23
+ type: 'string',
24
+ description: 'Directory path to scan (e.g. C:\\Users\\Name\\Downloads or /home/user/Projects).'
25
+ },
26
+ includeHidden: {
27
+ type: 'boolean',
28
+ description: 'Include hidden files and folders (default: false).'
29
+ },
30
+ minDuplicateBytes: {
31
+ type: 'integer',
32
+ description: 'Minimum file size in bytes for duplicate detection (default: 102400 = 100 KB).'
33
+ },
34
+ minLargeFileBytes: {
35
+ type: 'integer',
36
+ description: 'Minimum file size in bytes to flag as a large file (default: 104857600 = 100 MB).'
37
+ },
38
+ forgottenDays: {
39
+ type: 'integer',
40
+ description: 'Days since last access/modification to flag a file as forgotten (default: 90).'
41
+ }
42
+ },
43
+ required: ['path']
44
+ }
45
+ },
46
+ {
47
+ name: 'vacumify_get_dev_caches',
48
+ description:
49
+ 'Scan a workspace or Projects directory specifically for reclaimable developer caches (node_modules, .NET bin/obj, .venv, Rust/Maven target, __pycache__, Gradle, .next, dist, build) with Active/Dormant/Abandoned git activity status.',
50
+ inputSchema: {
51
+ type: 'object',
52
+ properties: {
53
+ path: {
54
+ type: 'string',
55
+ description: 'Root workspace or Projects directory path to scan.'
56
+ },
57
+ olderThanDays: {
58
+ type: 'integer',
59
+ description: 'Optional filter: only return caches in projects untouched for at least N days.'
60
+ }
61
+ },
62
+ required: ['path']
63
+ }
64
+ },
65
+ {
66
+ name: 'vacumify_get_safe_junk',
67
+ description:
68
+ 'Identify safe-to-delete junk candidates in a folder: redundant duplicate copies (preserving original) and obsolete installers (.msi/.exe/.dmp/old .log untouched >30 days).',
69
+ inputSchema: {
70
+ type: 'object',
71
+ properties: {
72
+ path: {
73
+ type: 'string',
74
+ description: 'Directory path to analyze.'
75
+ }
76
+ },
77
+ required: ['path']
78
+ }
79
+ },
80
+ {
81
+ name: 'vacumify_recycle_items',
82
+ description:
83
+ 'Safely move specified files or folders into the OS Recycle Bin / System Trash. NEVER permanently deletes files, and blocks critical OS/system paths.',
84
+ inputSchema: {
85
+ type: 'object',
86
+ properties: {
87
+ paths: {
88
+ type: 'array',
89
+ items: { type: 'string' },
90
+ description: 'List of absolute file or directory paths to move to Recycle Bin / Trash.'
91
+ },
92
+ dryRun: {
93
+ type: 'boolean',
94
+ description: 'If true, preview what would be recycled without moving any files (default: false).'
95
+ }
96
+ },
97
+ required: ['paths']
98
+ }
23
99
  }
100
+ ];
24
101
 
25
- // 3. Check ~/.vacumify auto-install directory
26
- const userHome = process.env.USERPROFILE || process.env.HOME || '';
27
- const autoInstallDir = path.join(userHome, '.vacumify');
28
- const autoInstallExe = path.join(autoInstallDir, 'Vacumify.exe');
29
- if (fs.existsSync(autoInstallExe)) return autoInstallExe;
30
-
31
- // 4. Search PATH on Windows
32
- if (process.platform === 'win32') {
33
- try {
34
- const stdout = execSync('where.exe Vacumify.exe', { stdio: ['pipe', 'pipe', 'ignore'], encoding: 'utf8' });
35
- const firstLine = stdout.trim().split(/\r?\n/)[0];
36
- if (firstLine && fs.existsSync(firstLine)) return firstLine;
37
- } catch (_) {}
102
+ const PROMPTS = [
103
+ {
104
+ name: 'audit-storage',
105
+ description: 'Comprehensive storage audit covering dev caches, duplicates, forgotten files, and large files.',
106
+ arguments: [
107
+ {
108
+ name: 'path',
109
+ description: 'Directory path to audit (optional; defaults to asking or current workspace).',
110
+ required: false
111
+ }
112
+ ]
113
+ },
114
+ {
115
+ name: 'duplicates',
116
+ description: 'Find duplicate file groups and safely recycle redundant copies.',
117
+ arguments: [
118
+ {
119
+ name: 'path',
120
+ description: 'Directory path to scan for duplicates (optional).',
121
+ required: false
122
+ }
123
+ ]
124
+ },
125
+ {
126
+ name: 'forgotten-files',
127
+ description: 'Find untouched/forgotten files older than a configurable day threshold (default 90 days).',
128
+ arguments: [
129
+ {
130
+ name: 'path',
131
+ description: 'Directory path to inspect (optional).',
132
+ required: false
133
+ },
134
+ {
135
+ name: 'days',
136
+ description: 'Inactivity threshold in days (default: 90).',
137
+ required: false
138
+ }
139
+ ]
140
+ },
141
+ {
142
+ name: 'large-files',
143
+ description: 'Find oversized files exceeding a size threshold (default 100 MB).',
144
+ arguments: [
145
+ {
146
+ name: 'path',
147
+ description: 'Directory path to inspect (optional).',
148
+ required: false
149
+ },
150
+ {
151
+ name: 'minSizeMb',
152
+ description: 'Minimum file size in MB (default: 100).',
153
+ required: false
154
+ }
155
+ ]
156
+ },
157
+ {
158
+ name: 'dev-caches',
159
+ description: 'Scan workspace for bloated developer caches scored by Active/Dormant/Abandoned project activity.',
160
+ arguments: [
161
+ {
162
+ name: 'path',
163
+ description: 'Workspace or Projects directory path (optional).',
164
+ required: false
165
+ },
166
+ {
167
+ name: 'olderThanDays',
168
+ description: 'Optional minimum days untouched filter.',
169
+ required: false
170
+ }
171
+ ]
38
172
  }
173
+ ];
39
174
 
40
- return null;
175
+ function sendMessage(msg) {
176
+ process.stdout.write(JSON.stringify(msg) + '\n');
41
177
  }
42
178
 
43
- function downloadAndExtractRelease() {
44
- if (process.platform !== 'win32') {
45
- console.error('[vacumify-mcp] Vacumify currently supports Windows (x64).');
46
- process.exit(1);
179
+ function sendResult(id, result) {
180
+ sendMessage({ jsonrpc: '2.0', id, result });
181
+ }
182
+
183
+ function sendError(id, code, message, data) {
184
+ const err = { code, message };
185
+ if (data !== undefined) err.data = data;
186
+ sendMessage({ jsonrpc: '2.0', id, error: err });
187
+ }
188
+
189
+ function toolTextResult(payload, isError = false) {
190
+ return {
191
+ content: [
192
+ {
193
+ type: 'text',
194
+ text: typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2)
195
+ }
196
+ ],
197
+ ...(isError ? { isError: true } : {})
198
+ };
199
+ }
200
+
201
+ function resolveValidDir(inputPath) {
202
+ if (!inputPath || typeof inputPath !== 'string' || !inputPath.trim()) {
203
+ throw new Error('Missing required "path" argument.');
204
+ }
205
+ const resolved = path.resolve(inputPath.trim());
206
+ if (!fs.existsSync(resolved)) {
207
+ throw new Error(`Directory not found: ${resolved}`);
47
208
  }
209
+ const stat = fs.statSync(resolved);
210
+ if (!stat.isDirectory()) {
211
+ throw new Error(`Path is not a directory: ${resolved}`);
212
+ }
213
+ return resolved;
214
+ }
48
215
 
49
- const userHome = process.env.USERPROFILE || process.env.HOME || '';
50
- const autoInstallDir = path.join(userHome, '.vacumify');
51
- const autoInstallExe = path.join(autoInstallDir, 'Vacumify.exe');
52
- const url = 'https://github.com/kuroi17/Vacumify/releases/latest/download/Vacumify-win-x64.zip';
216
+ function enrichActivity(targetPath, fallbackMs) {
217
+ const act = scanner.getProjectActivity(targetPath, fallbackMs);
218
+ return {
219
+ activityStatus: act.status,
220
+ daysUntouched: act.daysUntouched
221
+ };
222
+ }
53
223
 
54
- console.error('[vacumify-mcp] Vacumify.exe not found locally. Downloading latest release from GitHub...');
224
+ async function handleVacumifyScan(args) {
225
+ const targetPath = resolveValidDir(args.path);
226
+ const includeHidden = Boolean(args.includeHidden);
227
+ const minDuplicateBytes = Number.isFinite(args.minDuplicateBytes)
228
+ ? Math.max(1, Number(args.minDuplicateBytes))
229
+ : 100 * 1024;
230
+ const minLargeFileBytes = Number.isFinite(args.minLargeFileBytes)
231
+ ? Math.max(1, Number(args.minLargeFileBytes))
232
+ : 100 * 1024 * 1024;
233
+ const forgottenDays = Number.isFinite(args.forgottenDays)
234
+ ? Math.max(1, Number(args.forgottenDays))
235
+ : 90;
55
236
 
56
- try {
57
- if (!fs.existsSync(autoInstallDir)) fs.mkdirSync(autoInstallDir, { recursive: true });
58
- const zipPath = path.join(autoInstallDir, 'Vacumify-win-x64.zip');
237
+ const result = await scanner.scanDirectory(targetPath, {
238
+ includeHidden,
239
+ minDuplicateBytes,
240
+ fastLargeSampling: true
241
+ });
59
242
 
60
- execSync(`powershell -Command "Invoke-WebRequest -Uri '${url}' -OutFile '${zipPath}'; Expand-Archive -Path '${zipPath}' -DestinationPath '${autoInstallDir}' -Force; Remove-Item '${zipPath}'"`, {
61
- stdio: ['ignore', 'inherit', 'inherit']
243
+ const nowMs = Date.now();
244
+ const forgottenCutoffMs = nowMs - forgottenDays * MS_PER_DAY;
245
+
246
+ const topLargeFiles = result.files
247
+ .filter((f) => f.size >= minLargeFileBytes)
248
+ .sort((a, b) => b.size - a.size)
249
+ .slice(0, 25)
250
+ .map((f) => ({
251
+ path: f.path,
252
+ name: f.name,
253
+ size: f.size,
254
+ sizeFormatted: scanner.formatBytes(f.size),
255
+ lastWrite: scanner.formatDate(f.lastWriteMs),
256
+ lastAccess: scanner.formatDate(f.lastAccessMs),
257
+ ...enrichActivity(f.path, f.lastWriteMs)
258
+ }));
259
+
260
+ const forgottenAll = result.files.filter(
261
+ (f) => Math.max(f.lastAccessMs || 0, f.lastWriteMs || 0) < forgottenCutoffMs
262
+ );
263
+ const topForgottenFiles = forgottenAll
264
+ .sort((a, b) => b.size - a.size)
265
+ .slice(0, 25)
266
+ .map((f) => {
267
+ const lastTouchMs = Math.max(f.lastAccessMs || 0, f.lastWriteMs || 0);
268
+ const daysIdle = Math.max(0, Math.floor((nowMs - lastTouchMs) / MS_PER_DAY));
269
+ return {
270
+ path: f.path,
271
+ name: f.name,
272
+ size: f.size,
273
+ sizeFormatted: scanner.formatBytes(f.size),
274
+ daysIdle,
275
+ lastAccess: scanner.formatDate(f.lastAccessMs),
276
+ lastWrite: scanner.formatDate(f.lastWriteMs),
277
+ ...enrichActivity(f.path, f.lastWriteMs)
278
+ };
62
279
  });
63
280
 
64
- if (fs.existsSync(autoInstallExe)) {
65
- console.error('[vacumify-mcp] Successfully installed Vacumify to ' + autoInstallDir);
66
- return autoInstallExe;
281
+ const groupsMap = new Map();
282
+ for (const f of result.files) {
283
+ if (!f.duplicateGroupId) continue;
284
+ let list = groupsMap.get(f.duplicateGroupId);
285
+ if (!list) {
286
+ list = [];
287
+ groupsMap.set(f.duplicateGroupId, list);
67
288
  }
68
- } catch (err) {
69
- console.error('[vacumify-mcp] Auto-download failed: ' + err.message);
289
+ list.push(f);
290
+ }
291
+
292
+ const topDuplicateGroups = Array.from(groupsMap.entries())
293
+ .map(([groupId, items]) => {
294
+ const sorted = items.slice().sort((a, b) => (a.lastWriteMs || 0) - (b.lastWriteMs || 0));
295
+ const unitSize = sorted[0]?.size || 0;
296
+ const reclaimableBytes = unitSize * Math.max(0, sorted.length - 1);
297
+ const anchor = sorted[0];
298
+ return {
299
+ groupId,
300
+ fileCount: sorted.length,
301
+ unitSize,
302
+ reclaimableBytes,
303
+ reclaimableFormatted: scanner.formatBytes(reclaimableBytes),
304
+ ...enrichActivity(anchor.path, anchor.lastWriteMs),
305
+ paths: sorted.map((x) => x.path)
306
+ };
307
+ })
308
+ .sort((a, b) => b.reclaimableBytes - a.reclaimableBytes)
309
+ .slice(0, 20);
310
+
311
+ const devCaches = result.devCaches
312
+ .slice()
313
+ .sort((a, b) => b.size - a.size)
314
+ .slice(0, 30)
315
+ .map((c) => ({
316
+ path: c.path,
317
+ projectName: c.projectName,
318
+ cacheType: c.cacheType,
319
+ size: c.size,
320
+ sizeFormatted: scanner.formatBytes(c.size),
321
+ lastModified: scanner.formatDate(c.lastModifiedMs),
322
+ ...enrichActivity(c.path, c.lastModifiedMs)
323
+ }));
324
+
325
+ return {
326
+ scannedPath: targetPath,
327
+ totalFiles: result.files.length,
328
+ totalBytes: result.bytesScanned,
329
+ totalFormatted: scanner.formatBytes(result.bytesScanned),
330
+ conditions: {
331
+ forgottenDays,
332
+ minLargeFileBytes,
333
+ minDuplicateBytes,
334
+ includeHidden
335
+ },
336
+ reclaimableDuplicateBytes: result.reclaimableDuplicateBytes,
337
+ reclaimableDuplicateFormatted: scanner.formatBytes(result.reclaimableDuplicateBytes),
338
+ duplicateGroupCount: groupsMap.size,
339
+ forgottenFilesCount: forgottenAll.length,
340
+ devCacheCount: result.devCaches.length,
341
+ devCacheTotalBytes: result.devCaches.reduce((acc, c) => acc + c.size, 0),
342
+ devCacheTotalFormatted: scanner.formatBytes(result.devCaches.reduce((acc, c) => acc + c.size, 0)),
343
+ topLargeFiles,
344
+ topForgottenFiles,
345
+ topDuplicateGroups,
346
+ devCaches,
347
+ errorsCount: result.errors.length
348
+ };
349
+ }
350
+
351
+ async function handleGetDevCaches(args) {
352
+ const targetPath = resolveValidDir(args.path);
353
+ const olderThanDays =
354
+ args.olderThanDays !== undefined && args.olderThanDays !== null
355
+ ? Math.max(0, Number(args.olderThanDays))
356
+ : null;
357
+
358
+ const result = await scanner.scanDirectory(targetPath, {
359
+ includeHidden: false,
360
+ minDuplicateBytes: 100 * 1024,
361
+ fastLargeSampling: true
362
+ });
363
+
364
+ let caches = result.devCaches.map((c) => {
365
+ const activity = scanner.getProjectActivity(c.path, c.lastModifiedMs);
366
+ return {
367
+ path: c.path,
368
+ projectName: c.projectName,
369
+ cacheType: c.cacheType,
370
+ size: c.size,
371
+ sizeFormatted: scanner.formatBytes(c.size),
372
+ lastModified: scanner.formatDate(c.lastModifiedMs),
373
+ activityStatus: activity.status,
374
+ daysUntouched: activity.daysUntouched,
375
+ projectRoot: activity.projectRoot
376
+ };
377
+ });
378
+
379
+ if (olderThanDays !== null && Number.isFinite(olderThanDays)) {
380
+ caches = caches.filter((c) => c.daysUntouched >= olderThanDays);
70
381
  }
71
- return null;
382
+
383
+ caches.sort((a, b) => b.size - a.size);
384
+ const totalBytes = caches.reduce((acc, c) => acc + c.size, 0);
385
+
386
+ return {
387
+ scannedPath: targetPath,
388
+ olderThanDays,
389
+ cacheCount: caches.length,
390
+ totalBytes,
391
+ totalFormatted: scanner.formatBytes(totalBytes),
392
+ caches
393
+ };
72
394
  }
73
395
 
74
- let exePath = findVacumifyExecutable() || downloadAndExtractRelease();
396
+ async function handleGetSafeJunk(args) {
397
+ const targetPath = resolveValidDir(args.path);
398
+ const result = await scanner.scanDirectory(targetPath, {
399
+ includeHidden: false,
400
+ minDuplicateBytes: 100 * 1024,
401
+ fastLargeSampling: true
402
+ });
403
+
404
+ const junk = scanner.identifySafeJunk(result.files);
405
+ const totalBytes = junk.reduce((acc, f) => acc + f.size, 0);
75
406
 
76
- if (!exePath) {
77
- console.error('[vacumify-mcp] Error: Vacumify.exe not found.');
78
- console.error('[vacumify-mcp] Please either:');
79
- console.error(' 1. Set VACUMIFY_PATH environment variable to the path of Vacumify.exe');
80
- console.error(' 2. Place Vacumify.exe in your PATH');
81
- console.error(' 3. Or build the project: dotnet publish StorageCleaner/StorageCleaner/StorageCleaner.csproj -c Release -r win-x64 --self-contained true');
82
- process.exit(1);
407
+ return {
408
+ scannedPath: targetPath,
409
+ candidateCount: junk.length,
410
+ totalBytes,
411
+ totalFormatted: scanner.formatBytes(totalBytes),
412
+ candidates: junk
413
+ .slice()
414
+ .sort((a, b) => b.size - a.size)
415
+ .slice(0, 100)
416
+ .map((f) => ({
417
+ path: f.path,
418
+ name: f.name,
419
+ size: f.size,
420
+ sizeFormatted: scanner.formatBytes(f.size),
421
+ reason: f.duplicateGroupId ? 'redundant_duplicate' : 'obsolete_installer_or_dump',
422
+ lastWrite: scanner.formatDate(f.lastWriteMs)
423
+ }))
424
+ };
83
425
  }
84
426
 
85
- const child = spawn(exePath, ['--mcp'], {
86
- stdio: 'inherit',
87
- windowsHide: true
88
- });
427
+ async function handleRecycleItems(args) {
428
+ if (!Array.isArray(args.paths) || args.paths.length === 0) {
429
+ throw new Error('Argument "paths" must be a non-empty array of absolute file/folder paths.');
430
+ }
431
+ const dryRun = Boolean(args.dryRun);
432
+ return await scanner.recycleItems(args.paths, dryRun);
433
+ }
89
434
 
90
- child.on('error', (err) => {
91
- console.error(`[vacumify-mcp] Failed to spawn Vacumify: ${err.message}`);
92
- process.exit(1);
93
- });
435
+ function getPromptResponse(name, args = {}) {
436
+ const target = args.path ? `"${args.path}"` : 'the target folder (ask the user if not specified)';
437
+ switch (name) {
438
+ case 'audit-storage':
439
+ return {
440
+ description: 'Comprehensive storage audit using Vacumify MCP tools.',
441
+ messages: [
442
+ {
443
+ role: 'user',
444
+ content: {
445
+ type: 'text',
446
+ text:
447
+ `Run a full storage audit on ${target} using \`vacumify_scan\` and \`vacumify_get_dev_caches\`.\n` +
448
+ 'Summarize reclaimed-space opportunities across four buckets:\n' +
449
+ '1. Developer caches (node_modules, .NET bin/obj, .venv, target, etc.) grouped by project activity (ACTIVE / DORMANT / ABANDONED).\n' +
450
+ '2. Redundant duplicate file groups (keep oldest original, list redundant copies).\n' +
451
+ '3. Forgotten files untouched for 90+ days (`forgottenDays`).\n' +
452
+ '4. Large files exceeding 100 MB (`minLargeFileBytes`).\n' +
453
+ 'Do NOT recycle anything without explicit user confirmation. When approved, always move items via `vacumify_recycle_items` (Recycle Bin / System Trash, never permanent delete).'
454
+ }
455
+ }
456
+ ]
457
+ };
458
+ case 'duplicates':
459
+ return {
460
+ description: 'Find duplicate file groups and safely recycle redundant copies.',
461
+ messages: [
462
+ {
463
+ role: 'user',
464
+ content: {
465
+ type: 'text',
466
+ text:
467
+ `Scan ${target} for duplicate files using \`vacumify_scan\` (respecting \`minDuplicateBytes\`, default 100 KB) and \`vacumify_get_safe_junk\`.\n` +
468
+ 'Present each duplicate group clearly with the preserved original copy and redundant copies, sorted by reclaimable size.\n' +
469
+ 'Ask the user before calling `vacumify_recycle_items` so redundant copies go safely to Recycle Bin / System Trash.'
470
+ }
471
+ }
472
+ ]
473
+ };
474
+ case 'forgotten-files': {
475
+ const days = args.days || '90';
476
+ return {
477
+ description: 'Find untouched files exceeding a day threshold.',
478
+ messages: [
479
+ {
480
+ role: 'user',
481
+ content: {
482
+ type: 'text',
483
+ text:
484
+ `Scan ${target} using \`vacumify_scan\` with \`forgottenDays: ${days}\`.\n` +
485
+ `List the top forgotten files untouched for at least ${days} days, including their size, last-accessed date, and project activity status.\n` +
486
+ 'Confirm with the user before recycling any files via `vacumify_recycle_items`.'
487
+ }
488
+ }
489
+ ]
490
+ };
491
+ }
492
+ case 'large-files': {
493
+ const minMb = args.minSizeMb || '100';
494
+ const minBytes = Math.max(1, Number(minMb) || 100) * 1024 * 1024;
495
+ return {
496
+ description: 'Find oversized files above a configurable MB threshold.',
497
+ messages: [
498
+ {
499
+ role: 'user',
500
+ content: {
501
+ type: 'text',
502
+ text:
503
+ `Scan ${target} using \`vacumify_scan\` with \`minLargeFileBytes: ${minBytes}\` (${minMb} MB).\n` +
504
+ 'Rank the largest files with sizes, last modified dates, and activity context.\n' +
505
+ 'Confirm with the user before recycling any files via `vacumify_recycle_items`.'
506
+ }
507
+ }
508
+ ]
509
+ };
510
+ }
511
+ case 'dev-caches': {
512
+ const olderClause = args.olderThanDays
513
+ ? ` with \`olderThanDays: ${args.olderThanDays}\``
514
+ : '';
515
+ return {
516
+ description: 'Find bloated developer caches with Active/Dormant/Abandoned context.',
517
+ messages: [
518
+ {
519
+ role: 'user',
520
+ content: {
521
+ type: 'text',
522
+ text:
523
+ `Scan ${target} using \`vacumify_get_dev_caches\`${olderClause}.\n` +
524
+ 'Highlight ABANDONED and DORMANT project caches first while warning against deleting ACTIVE workspace dependencies unless the user confirms.\n' +
525
+ 'Always use `vacumify_recycle_items` (Recycle Bin / System Trash) when cleaning approved caches.'
526
+ }
527
+ }
528
+ ]
529
+ };
530
+ }
531
+ default:
532
+ return null;
533
+ }
534
+ }
94
535
 
95
- child.on('exit', (code, signal) => {
96
- process.exit(code ?? (signal ? 1 : 0));
536
+ async function handleRequest(msg) {
537
+ const { id, method, params } = msg;
538
+ const isNotification = id === undefined || id === null;
539
+
540
+ try {
541
+ switch (method) {
542
+ case 'initialize': {
543
+ sendResult(id, {
544
+ protocolVersion: PROTOCOL_VERSION,
545
+ capabilities: {
546
+ tools: {},
547
+ prompts: {}
548
+ },
549
+ serverInfo: {
550
+ name: SERVER_NAME,
551
+ version: SERVER_VERSION
552
+ }
553
+ });
554
+ return;
555
+ }
556
+ case 'notifications/initialized':
557
+ case 'initialized':
558
+ return;
559
+ case 'ping': {
560
+ if (!isNotification) sendResult(id, {});
561
+ return;
562
+ }
563
+ case 'tools/list': {
564
+ sendResult(id, { tools: TOOLS });
565
+ return;
566
+ }
567
+ case 'tools/call': {
568
+ const toolName = params?.name;
569
+ const args = params?.arguments || {};
570
+ try {
571
+ let data;
572
+ if (toolName === 'vacumify_scan') {
573
+ data = await handleVacumifyScan(args);
574
+ } else if (toolName === 'vacumify_get_dev_caches') {
575
+ data = await handleGetDevCaches(args);
576
+ } else if (toolName === 'vacumify_get_safe_junk') {
577
+ data = await handleGetSafeJunk(args);
578
+ } else if (toolName === 'vacumify_recycle_items') {
579
+ data = await handleRecycleItems(args);
580
+ } else {
581
+ sendError(id, -32601, `Unknown tool: ${toolName}`);
582
+ return;
583
+ }
584
+ sendResult(id, toolTextResult(data));
585
+ } catch (toolErr) {
586
+ sendResult(id, toolTextResult({ error: toolErr.message || String(toolErr) }, true));
587
+ }
588
+ return;
589
+ }
590
+ case 'prompts/list': {
591
+ sendResult(id, { prompts: PROMPTS });
592
+ return;
593
+ }
594
+ case 'prompts/get': {
595
+ const promptName = params?.name;
596
+ const promptRes = getPromptResponse(promptName, params?.arguments || {});
597
+ if (!promptRes) {
598
+ sendError(id, -32602, `Unknown prompt: ${promptName}`);
599
+ return;
600
+ }
601
+ sendResult(id, promptRes);
602
+ return;
603
+ }
604
+ default: {
605
+ if (!isNotification) {
606
+ sendError(id, -32601, `Method not found: ${method}`);
607
+ }
608
+ }
609
+ }
610
+ } catch (err) {
611
+ if (!isNotification) {
612
+ sendError(id, -32603, err?.message || 'Internal error');
613
+ }
614
+ }
615
+ }
616
+
617
+ const rl = readline.createInterface({
618
+ input: process.stdin,
619
+ crlfDelay: Infinity
97
620
  });
98
621
 
622
+ let pending = Promise.resolve();
623
+ rl.on('line', (line) => {
624
+ const trimmed = line.trim();
625
+ if (!trimmed) return;
626
+ let parsed;
627
+ try {
628
+ parsed = JSON.parse(trimmed);
629
+ } catch (e) {
630
+ sendError(null, -32700, 'Parse error');
631
+ return;
632
+ }
633
+ pending = pending.then(() => handleRequest(parsed));
634
+ });
package/lib/scanner.js ADDED
@@ -0,0 +1,603 @@
1
+ const fs = require('fs');
2
+ const fsp = fs.promises;
3
+ const path = require('path');
4
+ const crypto = require('crypto');
5
+ const os = require('os');
6
+ const { spawnSync } = require('child_process');
7
+
8
+ const LARGE_FILE_THRESHOLD = 16 * 1024 * 1024; // 16 MB
9
+ const PREFIX_BYTES = 1024;
10
+ const SAMPLE_BLOCK_BYTES = 64 * 1024;
11
+ const HASH_CONCURRENCY = 16;
12
+
13
+ const ALWAYS_EXCLUDED_FOLDERS = new Set([
14
+ '.git',
15
+ 'system volume information',
16
+ '$recycle.bin',
17
+ 'windows',
18
+ 'program files',
19
+ 'program files (x86)',
20
+ 'programdata'
21
+ ]);
22
+
23
+ const HIDDEN_DEV_FOLDERS = new Set([
24
+ '.cache',
25
+ '.npm',
26
+ '.yarn',
27
+ '.pnpm-store',
28
+ '.gradle',
29
+ '.m2',
30
+ '.nuget',
31
+ '.cargo',
32
+ '.rustup',
33
+ '.docker',
34
+ '.android',
35
+ '.vscode',
36
+ '.vs'
37
+ ]);
38
+
39
+ function formatBytes(bytes) {
40
+ if (!bytes || bytes <= 0) return '0 B';
41
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
42
+ let idx = 0;
43
+ let val = bytes;
44
+ while (val >= 1024 && idx < units.length - 1) {
45
+ val /= 1024;
46
+ idx++;
47
+ }
48
+ return idx === 0 ? `${Math.round(val)} B` : `${val.toFixed(2).replace(/\.?0+$/, '')} ${units[idx]}`;
49
+ }
50
+
51
+ function formatDate(ms) {
52
+ const d = new Date(ms);
53
+ const pad = (n) => String(n).padStart(2, '0');
54
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
55
+ }
56
+
57
+ function getProtectedRoots() {
58
+ if (process.platform === 'win32') {
59
+ const winDir = process.env.WINDIR || 'C:\\Windows';
60
+ const progFiles = process.env.ProgramFiles || 'C:\\Program Files';
61
+ const progFilesX86 = process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';
62
+ const progData = process.env.ProgramData || 'C:\\ProgramData';
63
+ const appData = process.env.APPDATA || '';
64
+ const localAppData = process.env.LOCALAPPDATA || '';
65
+ return [winDir, progFiles, progFilesX86, progData, appData, localAppData]
66
+ .filter(Boolean)
67
+ .map((p) => path.resolve(p).toLowerCase());
68
+ }
69
+ return ['/system', '/library', '/bin', '/sbin', '/usr', '/etc', '/var', '/dev', '/proc', '/sys']
70
+ .map((p) => path.resolve(p).toLowerCase());
71
+ }
72
+
73
+ const PROTECTED_ROOTS = getProtectedRoots();
74
+
75
+ function isProtectedRoot(targetPath) {
76
+ try {
77
+ const norm = path.resolve(targetPath).toLowerCase();
78
+ return PROTECTED_ROOTS.includes(norm);
79
+ } catch {
80
+ return true;
81
+ }
82
+ }
83
+
84
+ function isProtectedPath(targetPath) {
85
+ try {
86
+ const norm = path.resolve(targetPath).toLowerCase();
87
+ return PROTECTED_ROOTS.some((root) => norm === root || norm.startsWith(root + path.sep));
88
+ } catch {
89
+ return true;
90
+ }
91
+ }
92
+
93
+ async function parentHasAnyFile(parentDir, patterns) {
94
+ if (!parentDir) return false;
95
+ try {
96
+ const entries = await fsp.readdir(parentDir);
97
+ for (const name of entries) {
98
+ const lower = name.toLowerCase();
99
+ for (const pat of patterns) {
100
+ if (pat.startsWith('*.')) {
101
+ if (lower.endsWith(pat.slice(1))) return true;
102
+ } else if (lower === pat.toLowerCase()) {
103
+ return true;
104
+ }
105
+ }
106
+ }
107
+ } catch {}
108
+ return false;
109
+ }
110
+
111
+ async function isDevCacheFolder(folderName, parentDir) {
112
+ const lower = folderName.toLowerCase();
113
+ if (lower === 'node_modules') return 'node_modules';
114
+ if (lower === 'venv' || lower === '.venv' || lower === '__pycache__') return 'Python venv';
115
+ if (lower === '.gradle') return 'Gradle';
116
+
117
+ if (lower === 'target' && (await parentHasAnyFile(parentDir, ['Cargo.toml', 'pom.xml']))) {
118
+ return 'Rust target';
119
+ }
120
+ if ((lower === 'bin' || lower === 'obj') && (await parentHasAnyFile(parentDir, ['*.csproj', '*.fsproj', '*.vbproj', '*.sln']))) {
121
+ return '.NET bin/obj';
122
+ }
123
+ return null;
124
+ }
125
+
126
+ async function fastGetDirectorySize(dirPath) {
127
+ let total = 0;
128
+ const queue = [dirPath];
129
+ while (queue.length > 0) {
130
+ const current = queue.pop();
131
+ let entries;
132
+ try {
133
+ entries = await fsp.readdir(current, { withFileTypes: true });
134
+ } catch {
135
+ continue;
136
+ }
137
+ for (const entry of entries) {
138
+ if (entry.isSymbolicLink()) continue;
139
+ const full = path.join(current, entry.name);
140
+ if (entry.isDirectory()) {
141
+ queue.push(full);
142
+ } else if (entry.isFile()) {
143
+ try {
144
+ const st = await fsp.stat(full);
145
+ total += st.size;
146
+ } catch {}
147
+ }
148
+ }
149
+ }
150
+ return total;
151
+ }
152
+
153
+ function getExtension(fileName) {
154
+ const ext = path.extname(fileName);
155
+ return ext ? ext.slice(1).toUpperCase() : '';
156
+ }
157
+
158
+ async function computePrefixHash(filePath, size) {
159
+ const len = Math.min(PREFIX_BYTES, size);
160
+ const fh = await fsp.open(filePath, 'r');
161
+ try {
162
+ const buf = Buffer.allocUnsafe(len);
163
+ const { bytesRead } = await fh.read(buf, 0, len, 0);
164
+ return crypto.createHash('sha256').update(buf.subarray(0, bytesRead)).digest('hex');
165
+ } finally {
166
+ await fh.close();
167
+ }
168
+ }
169
+
170
+ async function computeContentHash(filePath, size, fastLargeSampling = true) {
171
+ if (!fastLargeSampling || size <= LARGE_FILE_THRESHOLD) {
172
+ return new Promise((resolve, reject) => {
173
+ const hash = crypto.createHash('sha256');
174
+ const stream = fs.createReadStream(filePath, { highWaterMark: 128 * 1024 });
175
+ stream.on('data', (chunk) => hash.update(chunk));
176
+ stream.on('end', () => resolve(hash.digest('hex')));
177
+ stream.on('error', reject);
178
+ });
179
+ }
180
+
181
+ // 8-point distributed sampling for files > 16 MB
182
+ const fh = await fsp.open(filePath, 'r');
183
+ try {
184
+ const hash = crypto.createHash('sha256');
185
+ const sizeBuf = Buffer.allocUnsafe(8);
186
+ sizeBuf.writeBigInt64LE(BigInt(size));
187
+ hash.update(sizeBuf);
188
+
189
+ const blocks = 8;
190
+ const buf = Buffer.allocUnsafe(SAMPLE_BLOCK_BYTES);
191
+ for (let i = 0; i < blocks; i++) {
192
+ const offset = i === blocks - 1
193
+ ? Math.max(0, size - SAMPLE_BLOCK_BYTES)
194
+ : Math.floor((i * (size - SAMPLE_BLOCK_BYTES)) / (blocks - 1));
195
+ const { bytesRead } = await fh.read(buf, 0, SAMPLE_BLOCK_BYTES, offset);
196
+ if (bytesRead > 0) {
197
+ hash.update(buf.subarray(0, bytesRead));
198
+ }
199
+ }
200
+ return `SAMPLE:${hash.digest('hex')}`;
201
+ } finally {
202
+ await fh.close();
203
+ }
204
+ }
205
+
206
+ async function mapConcurrent(items, limit, fn) {
207
+ const results = new Array(items.length);
208
+ let idx = 0;
209
+ async function worker() {
210
+ while (idx < items.length) {
211
+ const i = idx++;
212
+ results[i] = await fn(items[i], i);
213
+ }
214
+ }
215
+ const workers = Array.from({ length: Math.min(limit, items.length) }, () => worker());
216
+ await Promise.all(workers);
217
+ return results;
218
+ }
219
+
220
+ async function scanDirectory(rootPath, options = {}) {
221
+ const {
222
+ includeHidden = false,
223
+ minDuplicateBytes = 100 * 1024,
224
+ fastLargeSampling = true
225
+ } = options;
226
+
227
+ const resolvedRoot = path.resolve(rootPath);
228
+ if (!fs.existsSync(resolvedRoot)) {
229
+ throw new Error(`Directory does not exist: ${rootPath}`);
230
+ }
231
+
232
+ const files = [];
233
+ const devCaches = [];
234
+ const errors = [];
235
+ let bytesScanned = 0;
236
+
237
+ const queue = [resolvedRoot];
238
+ const seen = new Set([resolvedRoot.toLowerCase()]);
239
+
240
+ while (queue.length > 0) {
241
+ // Process batch concurrently
242
+ const batch = queue.splice(0, 16);
243
+ await Promise.all(batch.map(async (dir) => {
244
+ let entries;
245
+ try {
246
+ entries = await fsp.readdir(dir, { withFileTypes: true });
247
+ } catch (err) {
248
+ errors.push(`${dir}: ${err.message}`);
249
+ return;
250
+ }
251
+
252
+ for (const entry of entries) {
253
+ if (entry.isSymbolicLink()) continue;
254
+ const fullPath = path.join(dir, entry.name);
255
+
256
+ if (entry.isDirectory()) {
257
+ if (isProtectedRoot(fullPath)) continue;
258
+
259
+ const cacheType = await isDevCacheFolder(entry.name, dir);
260
+ if (cacheType) {
261
+ try {
262
+ const st = await fsp.stat(fullPath);
263
+ const cacheSize = await fastGetDirectorySize(fullPath);
264
+ const projName = path.basename(dir) || entry.name;
265
+ devCaches.push({
266
+ path: fullPath,
267
+ projectName: projName,
268
+ cacheType,
269
+ size: cacheSize,
270
+ lastModifiedMs: st.mtimeMs
271
+ });
272
+ } catch {}
273
+ continue;
274
+ }
275
+
276
+ const lowerName = entry.name.toLowerCase();
277
+ if (ALWAYS_EXCLUDED_FOLDERS.has(lowerName)) continue;
278
+ if (!includeHidden && (entry.name.startsWith('.') || HIDDEN_DEV_FOLDERS.has(lowerName))) continue;
279
+
280
+ const key = fullPath.toLowerCase();
281
+ if (!seen.has(key)) {
282
+ seen.add(key);
283
+ queue.push(fullPath);
284
+ }
285
+ } else if (entry.isFile()) {
286
+ try {
287
+ const st = await fsp.stat(fullPath);
288
+ bytesScanned += st.size;
289
+ files.push({
290
+ path: fullPath,
291
+ name: entry.name,
292
+ extension: getExtension(entry.name),
293
+ size: st.size,
294
+ lastAccessMs: st.atimeMs || st.mtimeMs,
295
+ lastWriteMs: st.mtimeMs,
296
+ duplicateGroupId: 0,
297
+ duplicateGroupCount: 0
298
+ });
299
+ } catch (err) {
300
+ errors.push(`${fullPath}: ${err.message}`);
301
+ }
302
+ }
303
+ }
304
+ }));
305
+ }
306
+
307
+ // Duplicate detection (3-stage pipeline)
308
+ const reclaimableDuplicateBytes = await assignDuplicateGroups(files, minDuplicateBytes, fastLargeSampling);
309
+ devCaches.sort((a, b) => b.size - a.size);
310
+
311
+ return {
312
+ files,
313
+ devCaches,
314
+ errors,
315
+ bytesScanned,
316
+ reclaimableDuplicateBytes
317
+ };
318
+ }
319
+
320
+ async function assignDuplicateGroups(files, minDuplicateBytes, fastLargeSampling) {
321
+ const bySize = new Map();
322
+ for (const f of files) {
323
+ if (f.size < minDuplicateBytes) continue;
324
+ let list = bySize.get(f.size);
325
+ if (!list) {
326
+ list = [];
327
+ bySize.set(f.size, list);
328
+ }
329
+ list.push(f);
330
+ }
331
+
332
+ const sizeCandidates = [];
333
+ for (const grp of bySize.values()) {
334
+ if (grp.length > 1) sizeCandidates.push(...grp);
335
+ }
336
+ if (sizeCandidates.length === 0) return 0;
337
+
338
+ // Stage 2: 1 KB prefix hash
339
+ const byPrefix = new Map();
340
+ await mapConcurrent(sizeCandidates, HASH_CONCURRENCY, async (f) => {
341
+ try {
342
+ const pHash = await computePrefixHash(f.path, f.size);
343
+ const key = `${f.size}:${pHash}`;
344
+ let list = byPrefix.get(key);
345
+ if (!list) {
346
+ list = [];
347
+ byPrefix.set(key, list);
348
+ }
349
+ list.push(f);
350
+ } catch {}
351
+ });
352
+
353
+ const prefixCandidates = [];
354
+ for (const grp of byPrefix.values()) {
355
+ if (grp.length > 1) prefixCandidates.push(...grp);
356
+ }
357
+ if (prefixCandidates.length === 0) return 0;
358
+
359
+ // Stage 3: Full / 8-point distributed SHA-256
360
+ const byContent = new Map();
361
+ await mapConcurrent(prefixCandidates, HASH_CONCURRENCY, async (f) => {
362
+ try {
363
+ const cHash = await computeContentHash(f.path, f.size, fastLargeSampling);
364
+ const key = `${f.size}:${cHash}`;
365
+ let list = byContent.get(key);
366
+ if (!list) {
367
+ list = [];
368
+ byContent.set(key, list);
369
+ }
370
+ list.push(f);
371
+ } catch {}
372
+ });
373
+
374
+ let groupId = 1;
375
+ let reclaimable = 0;
376
+ for (const grp of byContent.values()) {
377
+ if (grp.length < 2) continue;
378
+ const count = grp.length;
379
+ reclaimable += (count - 1) * grp[0].size;
380
+ for (const copy of grp) {
381
+ copy.duplicateGroupId = groupId;
382
+ copy.duplicateGroupCount = count;
383
+ }
384
+ groupId++;
385
+ }
386
+
387
+ return reclaimable;
388
+ }
389
+
390
+ function identifySafeJunk(files) {
391
+ const safeList = [];
392
+
393
+ // 1. Redundant duplicate copies (keep newest intact)
394
+ const dupGroups = new Map();
395
+ for (const f of files) {
396
+ if (f.duplicateGroupCount > 1) {
397
+ let arr = dupGroups.get(f.duplicateGroupId);
398
+ if (!arr) {
399
+ arr = [];
400
+ dupGroups.set(f.duplicateGroupId, arr);
401
+ }
402
+ arr.push(f);
403
+ }
404
+ }
405
+ for (const copies of dupGroups.values()) {
406
+ copies.sort((a, b) => b.lastWriteMs - a.lastWriteMs);
407
+ for (let i = 1; i < copies.length; i++) {
408
+ safeList.push(copies[i]);
409
+ }
410
+ }
411
+
412
+ // 2. Obsolete installers & crash dumps (> 30 days untouched)
413
+ const cutoffMs = Date.now() - 30 * 24 * 60 * 60 * 1000;
414
+ for (const f of files) {
415
+ if (f.duplicateGroupCount > 1) continue;
416
+ const ext = f.extension;
417
+ const lowerName = f.name.toLowerCase();
418
+ const isInstaller = ext === 'MSI' ||
419
+ (ext === 'EXE' && (lowerName.includes('setup') || lowerName.includes('installer') || lowerName.includes('install')));
420
+ const isCrashDump = ext === 'DMP' || (ext === 'LOG' && f.size > 20 * 1024 * 1024);
421
+
422
+ if ((isInstaller || isCrashDump) && f.lastAccessMs <= cutoffMs) {
423
+ safeList.push(f);
424
+ }
425
+ }
426
+
427
+ return safeList;
428
+ }
429
+
430
+ function getProjectActivity(targetPath, fallbackLastWriteMs) {
431
+ let current;
432
+ try {
433
+ const isDir = fs.existsSync(targetPath) && fs.statSync(targetPath).isDirectory();
434
+ current = isDir ? path.dirname(path.resolve(targetPath)) : path.dirname(path.resolve(targetPath));
435
+ } catch {
436
+ current = path.dirname(targetPath);
437
+ }
438
+
439
+ let projectRoot = current;
440
+ let lastTouchMs = fallbackLastWriteMs || Date.now();
441
+
442
+ try {
443
+ for (let depth = 0; depth < 4 && current; depth++) {
444
+ if (isProtectedRoot(current)) break;
445
+ const gitDir = path.join(current, '.git');
446
+ if (fs.existsSync(gitDir)) {
447
+ projectRoot = current;
448
+ const headLog = path.join(gitDir, 'logs', 'HEAD');
449
+ const gitIndex = path.join(gitDir, 'index');
450
+ if (fs.existsSync(headLog)) {
451
+ lastTouchMs = fs.statSync(headLog).mtimeMs;
452
+ } else if (fs.existsSync(gitIndex)) {
453
+ lastTouchMs = fs.statSync(gitIndex).mtimeMs;
454
+ } else {
455
+ lastTouchMs = fs.statSync(current).mtimeMs;
456
+ }
457
+ break;
458
+ }
459
+
460
+ const hasMarker =
461
+ fs.existsSync(path.join(current, 'package.json')) ||
462
+ fs.existsSync(path.join(current, 'Cargo.toml')) ||
463
+ fs.existsSync(path.join(current, 'pyproject.toml'));
464
+
465
+ if (hasMarker) {
466
+ projectRoot = current;
467
+ lastTouchMs = fs.statSync(current).mtimeMs;
468
+ break;
469
+ }
470
+
471
+ const parent = path.dirname(current);
472
+ if (parent === current) break;
473
+ current = parent;
474
+ }
475
+ } catch {}
476
+
477
+ const daysUntouched = Math.max(0, Math.floor((Date.now() - lastTouchMs) / (24 * 60 * 60 * 1000)));
478
+ let status = 'ABANDONED';
479
+ if (daysUntouched <= 14) status = 'ACTIVE';
480
+ else if (daysUntouched <= 90) status = 'DORMANT';
481
+
482
+ return { status, daysUntouched, projectRoot };
483
+ }
484
+
485
+ async function recycleItems(paths, dryRun = false) {
486
+ let recycled = 0;
487
+ let failed = 0;
488
+ let protectedSkipped = 0;
489
+ let recycledBytes = 0;
490
+ const recycledPaths = [];
491
+ const validTargets = [];
492
+
493
+ for (const p of paths) {
494
+ if (!p || isProtectedPath(p) || isProtectedRoot(p)) {
495
+ protectedSkipped++;
496
+ continue;
497
+ }
498
+ if (!fs.existsSync(p)) {
499
+ failed++;
500
+ continue;
501
+ }
502
+ try {
503
+ const st = fs.statSync(p);
504
+ const size = st.isDirectory() ? await fastGetDirectorySize(p) : st.size;
505
+ validTargets.push({ path: p, isDir: st.isDirectory(), size });
506
+ } catch {
507
+ failed++;
508
+ }
509
+ }
510
+
511
+ if (dryRun) {
512
+ for (const t of validTargets) {
513
+ recycled++;
514
+ recycledBytes += t.size;
515
+ recycledPaths.push(t.path);
516
+ }
517
+ return { dryRun: true, recycledCount: recycled, recycledBytes, recycledFormatted: formatBytes(recycledBytes), failedCount: failed, protectedSkipped, recycledPaths };
518
+ }
519
+
520
+ if (validTargets.length > 0) {
521
+ if (process.platform === 'win32') {
522
+ // Safe Windows Recycle Bin via Microsoft.VisualBasic.FileIO
523
+ const psScript = `
524
+ Add-Type -AssemblyName Microsoft.VisualBasic
525
+ $items = $env:VACUMIFY_RECYCLE_JSON | ConvertFrom-Json
526
+ foreach ($item in $items) {
527
+ try {
528
+ if ($item.isDir) {
529
+ [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($item.path, 'OnlyErrorDialogs', 'SendToRecycleBin')
530
+ } else {
531
+ [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($item.path, 'OnlyErrorDialogs', 'SendToRecycleBin')
532
+ }
533
+ Write-Output "OK:$($item.path)"
534
+ } catch {
535
+ Write-Output "ERR:$($item.path)"
536
+ }
537
+ }
538
+ `;
539
+ const encoded = Buffer.from(psScript, 'utf16le').toString('base64');
540
+ const res = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], {
541
+ env: { ...process.env, VACUMIFY_RECYCLE_JSON: JSON.stringify(validTargets) },
542
+ encoding: 'utf8'
543
+ });
544
+
545
+ const okSet = new Set();
546
+ if (res.stdout) {
547
+ for (const line of res.stdout.split(/\r?\n/)) {
548
+ if (line.startsWith('OK:')) okSet.add(line.slice(3).trim());
549
+ }
550
+ }
551
+ for (const t of validTargets) {
552
+ if (okSet.has(t.path) || !fs.existsSync(t.path)) {
553
+ recycled++;
554
+ recycledBytes += t.size;
555
+ recycledPaths.push(t.path);
556
+ } else {
557
+ failed++;
558
+ }
559
+ }
560
+ } else if (process.platform === 'darwin') {
561
+ for (const t of validTargets) {
562
+ const res = spawnSync('osascript', ['-e', `tell application "Finder" to delete POSIX file "${t.path.replace(/"/g, '\\"')}"`]);
563
+ if (res.status === 0 && !fs.existsSync(t.path)) {
564
+ recycled++;
565
+ recycledBytes += t.size;
566
+ recycledPaths.push(t.path);
567
+ } else {
568
+ failed++;
569
+ }
570
+ }
571
+ } else {
572
+ for (const t of validTargets) {
573
+ const res = spawnSync('gio', ['trash', t.path]);
574
+ if (res.status === 0 && !fs.existsSync(t.path)) {
575
+ recycled++;
576
+ recycledBytes += t.size;
577
+ recycledPaths.push(t.path);
578
+ } else {
579
+ failed++;
580
+ }
581
+ }
582
+ }
583
+ }
584
+
585
+ return {
586
+ dryRun: false,
587
+ recycledCount: recycled,
588
+ recycledBytes,
589
+ recycledFormatted: formatBytes(recycledBytes),
590
+ failedCount: failed,
591
+ protectedSkipped,
592
+ recycledPaths: recycledPaths.slice(0, 50)
593
+ };
594
+ }
595
+
596
+ module.exports = {
597
+ scanDirectory,
598
+ identifySafeJunk,
599
+ getProjectActivity,
600
+ recycleItems,
601
+ formatBytes,
602
+ formatDate
603
+ };
package/package.json CHANGED
@@ -1,26 +1,34 @@
1
- {
2
- "name": "vacumify-mcp",
3
- "version": "1.1.0",
4
- "description": "Model Context Protocol (MCP) server for Vacumify — Fast, local-first storage cleaner and duplicate finder for AI agents (Claude Code, Cursor, Antigravity, VS Code)",
5
- "main": "bin/vacumify-mcp.js",
6
- "bin": {
7
- "vacumify-mcp": "bin/vacumify-mcp.js"
8
- },
9
- "keywords": [
10
- "mcp",
11
- "model-context-protocol",
12
- "vacumify",
13
- "disk-cleaner",
14
- "duplicate-finder",
15
- "storage",
16
- "claude",
17
- "cursor",
18
- "ai-agent"
19
- ],
20
- "author": "kuroi17",
21
- "license": "MIT",
22
- "repository": {
23
- "type": "git",
24
- "url": "git+https://github.com/kuroi17/Vacumify.git"
25
- }
26
- }
1
+ {
2
+ "name": "vacumify-mcp",
3
+ "version": "1.2.0",
4
+ "description": "Standalone cross-platform Model Context Protocol (MCP) server for Vacumify — Pure Node.js zero-dependency storage cleaner, duplicate finder, and dev-cache auditor for AI agents (Windows, macOS, Linux)",
5
+ "main": "bin/vacumify-mcp.js",
6
+ "bin": {
7
+ "vacumify-mcp": "bin/vacumify-mcp.js"
8
+ },
9
+ "files": [
10
+ "bin/",
11
+ "lib/",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=18.0.0"
16
+ },
17
+ "keywords": [
18
+ "mcp",
19
+ "model-context-protocol",
20
+ "vacumify",
21
+ "disk-cleaner",
22
+ "duplicate-finder",
23
+ "storage",
24
+ "claude",
25
+ "cursor",
26
+ "ai-agent"
27
+ ],
28
+ "author": "kuroi17",
29
+ "license": "MIT",
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/kuroi17/Vacumify.git"
33
+ }
34
+ }