fuzzrunx 0.1.5 → 0.1.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fuzzrunx",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "Auto-correct mistyped commands and subcommands and re-run them safely.",
5
5
  "bin": {
6
6
  "fuzzrun": "bin/fuzzrun.js"
@@ -1,17 +1,36 @@
1
1
  'use strict';
2
2
 
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
3
6
  const installer = require('../src/installer');
4
7
 
5
8
  const skip = process.env.FUZZRUN_SKIP_ENABLE === '1';
6
9
 
10
+ function getStatePath() {
11
+ return path.join(os.homedir(), '.fuzzrun', 'state.json');
12
+ }
13
+
14
+ function writeState(next) {
15
+ const filePath = getStatePath();
16
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
17
+ fs.writeFileSync(filePath, JSON.stringify(next, null, 2), 'utf8');
18
+ }
19
+
7
20
  if (skip) {
8
- process.stdout.write('fuzzrun: auto-enable skipped\n');
21
+ process.stderr.write('fuzzrun: auto-enable skipped\n');
9
22
  process.exit(0);
10
23
  }
11
24
 
25
+ const foregroundScripts =
26
+ process.env.npm_config_foreground_scripts === 'true' ||
27
+ process.env.npm_config_foreground_scripts === '1';
28
+
12
29
  try {
13
30
  installer.enable({});
14
- process.stdout.write('FuzzRun is automatically enabled. Run "fuzzrun disable" to deactivate.\n');
31
+ process.stderr.write('FuzzRun is automatically enabled. Run "fuzzrun disable" to deactivate.\n');
32
+ writeState({ bannerShown: foregroundScripts, enableSucceeded: true });
15
33
  } catch (err) {
16
- process.stdout.write(`fuzzrun: auto-enable failed: ${err.message}\n`);
34
+ process.stderr.write(`fuzzrun: auto-enable failed: ${err.message}\n`);
35
+ writeState({ bannerShown: false, enableSucceeded: false, lastError: err.message });
17
36
  }
package/src/cli.js CHANGED
@@ -5,40 +5,41 @@
5
5
 
6
6
  const { spawnSync } = require('child_process');
7
7
  const fs = require('fs');
8
+ const os = require('os');
8
9
  const path = require('path');
9
10
  const installer = require('./installer');
10
-
11
- const MAX_DISTANCE = Number.isFinite(Number(process.env.FUZZRUN_MAX_DISTANCE))
12
- ? Math.max(1, Number(process.env.FUZZRUN_MAX_DISTANCE))
13
- : 1;
14
-
15
- const DEFAULT_PRIORITY_BASES = [
16
- 'git',
17
- 'npm',
18
- 'yarn',
19
- 'pnpm',
20
- 'node',
21
- 'python',
22
- 'python3',
23
- 'pip',
24
- 'pip3',
25
- 'docker',
26
- 'kubectl',
27
- 'gh',
28
- 'go',
29
- 'cargo',
30
- 'dotnet',
31
- 'java',
32
- 'mvn',
33
- 'gradle'
34
- ];
35
- const ENV_PRIORITY_BASES = (process.env.FUZZRUN_PREFER_BASES || '')
36
- .split(',')
37
- .map((value) => normalizeToken(value).trim())
38
- .filter(Boolean);
39
- const PRIORITY_BASES = new Set([...DEFAULT_PRIORITY_BASES, ...ENV_PRIORITY_BASES]);
40
-
41
- const DANGEROUS_BASE = new Set(['rm', 'mv', 'dd', 'shutdown', 'reboot', 'halt', 'poweroff']);
11
+
12
+ const MAX_DISTANCE = Number.isFinite(Number(process.env.FUZZRUN_MAX_DISTANCE))
13
+ ? Math.max(1, Number(process.env.FUZZRUN_MAX_DISTANCE))
14
+ : 1;
15
+
16
+ const DEFAULT_PRIORITY_BASES = [
17
+ 'git',
18
+ 'npm',
19
+ 'yarn',
20
+ 'pnpm',
21
+ 'node',
22
+ 'python',
23
+ 'python3',
24
+ 'pip',
25
+ 'pip3',
26
+ 'docker',
27
+ 'kubectl',
28
+ 'gh',
29
+ 'go',
30
+ 'cargo',
31
+ 'dotnet',
32
+ 'java',
33
+ 'mvn',
34
+ 'gradle'
35
+ ];
36
+ const ENV_PRIORITY_BASES = (process.env.FUZZRUN_PREFER_BASES || '')
37
+ .split(',')
38
+ .map((value) => normalizeToken(value).trim())
39
+ .filter(Boolean);
40
+ const PRIORITY_BASES = new Set([...DEFAULT_PRIORITY_BASES, ...ENV_PRIORITY_BASES]);
41
+
42
+ const DANGEROUS_BASE = new Set(['rm', 'mv', 'dd', 'shutdown', 'reboot', 'halt', 'poweroff']);
42
43
 
43
44
  const COMMON_SUBCOMMANDS = {
44
45
  git: [
@@ -174,31 +175,31 @@ const COMMON_SUBCOMMANDS = {
174
175
  'drain',
175
176
  'uncordon'
176
177
  ],
177
- gh: ['auth', 'repo', 'issue', 'pr', 'gist', 'alias', 'api', 'search', 'run', 'workflow', 'status', 'label']
178
- };
179
-
180
- const SAFE_SUBCOMMAND_BASES = new Set(Object.keys(COMMON_SUBCOMMANDS));
181
- const ALLOW_ANY_SUBCOMMANDS = process.env.FUZZRUN_ALLOW_ANY_SUBCOMMANDS === '1';
182
- const SCRIPT_BASES = new Set(['npm', 'yarn', 'pnpm']);
183
- const RISKY_ARG_PATTERNS = [
184
- /^-f$/,
185
- /^-rf$/,
186
- /^-fr$/,
187
- /^--force$/i,
188
- /^--hard$/i,
189
- /^--delete$/i,
190
- /^--purge$/i,
191
- /^--no-preserve-root$/i
192
- ];
193
- const SCRIPT_ERROR_PATTERNS = [
194
- /missing script/i,
195
- /unknown script/i,
196
- /script.*not found/i,
197
- /couldn'?t find.*script/i,
198
- /command ".*" not found/i
199
- ];
200
- const GIT_PATHSPEC_PATTERN = /pathspec .* did not match/i;
201
-
178
+ gh: ['auth', 'repo', 'issue', 'pr', 'gist', 'alias', 'api', 'search', 'run', 'workflow', 'status', 'label']
179
+ };
180
+
181
+ const SAFE_SUBCOMMAND_BASES = new Set(Object.keys(COMMON_SUBCOMMANDS));
182
+ const ALLOW_ANY_SUBCOMMANDS = process.env.FUZZRUN_ALLOW_ANY_SUBCOMMANDS === '1';
183
+ const SCRIPT_BASES = new Set(['npm', 'yarn', 'pnpm']);
184
+ const RISKY_ARG_PATTERNS = [
185
+ /^-f$/,
186
+ /^-rf$/,
187
+ /^-fr$/,
188
+ /^--force$/i,
189
+ /^--hard$/i,
190
+ /^--delete$/i,
191
+ /^--purge$/i,
192
+ /^--no-preserve-root$/i
193
+ ];
194
+ const SCRIPT_ERROR_PATTERNS = [
195
+ /missing script/i,
196
+ /unknown script/i,
197
+ /script.*not found/i,
198
+ /couldn'?t find.*script/i,
199
+ /command ".*" not found/i
200
+ ];
201
+ const GIT_PATHSPEC_PATTERN = /pathspec .* did not match/i;
202
+
202
203
  const suggestionPatterns = [
203
204
  /The most similar command is\s+([^\s]+)/i,
204
205
  /The most similar commands are:\s*\n\s*([^\s]+)/i,
@@ -207,57 +208,79 @@ const suggestionPatterns = [
207
208
  /Perhaps you meant\s+['"]?([A-Za-z0-9:_-]+)['"]?\??/i
208
209
  ];
209
210
 
210
- function normalizeToken(value) {
211
- return String(value || '').toLowerCase();
211
+ function getStatePath() {
212
+ return path.join(os.homedir(), '.fuzzrun', 'state.json');
212
213
  }
213
214
 
214
- function commandKey(command) {
215
- const base = path.basename(String(command || ''));
216
- const ext = path.extname(base);
217
- return normalizeToken(ext ? base.slice(0, -ext.length) : base);
215
+ function readState() {
216
+ try {
217
+ const raw = fs.readFileSync(getStatePath(), 'utf8');
218
+ return JSON.parse(raw);
219
+ } catch (err) {
220
+ return null;
221
+ }
218
222
  }
219
223
 
220
- function isInteractiveCommand(command, args) {
221
- const key = commandKey(command);
222
- if (INTERACTIVE_BASES.has(key)) return true;
223
- const subcommand = args && args.length ? normalizeToken(args[0]) : '';
224
- if (subcommand && INTERACTIVE_SUBCOMMANDS[key] && INTERACTIVE_SUBCOMMANDS[key].has(subcommand)) {
225
- return true;
224
+ function writeState(next) {
225
+ try {
226
+ const filePath = getStatePath();
227
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
228
+ fs.writeFileSync(filePath, JSON.stringify(next, null, 2), 'utf8');
229
+ } catch (err) {
230
+ // Best-effort only.
226
231
  }
227
- return false;
228
232
  }
229
233
 
230
- function damerauLevenshtein(a, b, maxDistance = 2) {
231
- const aNorm = normalizeToken(a);
232
- const bNorm = normalizeToken(b);
233
- if (aNorm === bNorm) return 0;
234
- if (Math.abs(aNorm.length - bNorm.length) > maxDistance) {
235
- return maxDistance + 1;
236
- }
237
- const dp = Array.from({ length: aNorm.length + 1 }, () => new Array(bNorm.length + 1).fill(0));
238
- for (let i = 0; i <= aNorm.length; i += 1) dp[i][0] = i;
239
- for (let j = 0; j <= bNorm.length; j += 1) dp[0][j] = j;
240
- for (let i = 1; i <= aNorm.length; i += 1) {
241
- let rowMin = maxDistance + 1;
242
- for (let j = 1; j <= bNorm.length; j += 1) {
243
- const cost = aNorm[i - 1] === bNorm[j - 1] ? 0 : 1;
244
- let value = Math.min(
245
- dp[i - 1][j] + 1,
246
- dp[i][j - 1] + 1,
247
- dp[i - 1][j - 1] + cost
248
- );
249
- if (i > 1 && j > 1 && aNorm[i - 1] === bNorm[j - 2] && aNorm[i - 2] === bNorm[j - 1]) {
250
- value = Math.min(value, dp[i - 2][j - 2] + 1);
251
- }
252
- dp[i][j] = value;
253
- if (value < rowMin) rowMin = value;
254
- }
255
- if (rowMin > maxDistance) {
256
- return maxDistance + 1;
257
- }
234
+ function showInstallBannerOnce() {
235
+ const state = readState() || {};
236
+ if (state.bannerShown) return;
237
+ const message =
238
+ state.enableSucceeded === false
239
+ ? 'FuzzRun auto-enable failed during install. Run "fuzzrun enable" to activate.\n'
240
+ : 'FuzzRun is automatically enabled. Run "fuzzrun disable" to deactivate.\n';
241
+ process.stderr.write(message);
242
+ state.bannerShown = true;
243
+ if (typeof state.enableSucceeded === 'undefined') {
244
+ state.enableSucceeded = true;
258
245
  }
259
- return dp[aNorm.length][bNorm.length];
246
+ writeState(state);
260
247
  }
248
+
249
+ function normalizeToken(value) {
250
+ return String(value || '').toLowerCase();
251
+ }
252
+
253
+ function damerauLevenshtein(a, b, maxDistance = 2) {
254
+ const aNorm = normalizeToken(a);
255
+ const bNorm = normalizeToken(b);
256
+ if (aNorm === bNorm) return 0;
257
+ if (Math.abs(aNorm.length - bNorm.length) > maxDistance) {
258
+ return maxDistance + 1;
259
+ }
260
+ const dp = Array.from({ length: aNorm.length + 1 }, () => new Array(bNorm.length + 1).fill(0));
261
+ for (let i = 0; i <= aNorm.length; i += 1) dp[i][0] = i;
262
+ for (let j = 0; j <= bNorm.length; j += 1) dp[0][j] = j;
263
+ for (let i = 1; i <= aNorm.length; i += 1) {
264
+ let rowMin = maxDistance + 1;
265
+ for (let j = 1; j <= bNorm.length; j += 1) {
266
+ const cost = aNorm[i - 1] === bNorm[j - 1] ? 0 : 1;
267
+ let value = Math.min(
268
+ dp[i - 1][j] + 1,
269
+ dp[i][j - 1] + 1,
270
+ dp[i - 1][j - 1] + cost
271
+ );
272
+ if (i > 1 && j > 1 && aNorm[i - 1] === bNorm[j - 2] && aNorm[i - 2] === bNorm[j - 1]) {
273
+ value = Math.min(value, dp[i - 2][j - 2] + 1);
274
+ }
275
+ dp[i][j] = value;
276
+ if (value < rowMin) rowMin = value;
277
+ }
278
+ if (rowMin > maxDistance) {
279
+ return maxDistance + 1;
280
+ }
281
+ }
282
+ return dp[aNorm.length][bNorm.length];
283
+ }
261
284
 
262
285
  function collectPathCommands() {
263
286
  const names = new Set();
@@ -291,103 +314,46 @@ function collectPathCommands() {
291
314
  return names;
292
315
  }
293
316
 
294
- const PATH_COMMANDS = collectPathCommands();
295
- const RESOLVE_CACHE = new Map();
296
- const PATHEXT = (process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD')
297
- .split(';')
298
- .map((value) => value.toLowerCase())
299
- .filter(Boolean);
300
- const INTERACTIVE_BASES = new Set(
301
- (process.env.FUZZRUN_INTERACTIVE_BASES || 'npm,npx,yarn,pnpm')
302
- .split(',')
303
- .map((value) => normalizeToken(value).trim())
304
- .filter(Boolean)
305
- );
306
- const INTERACTIVE_SUBCOMMANDS = {
307
- npm: new Set(['publish', 'login', 'adduser']),
308
- yarn: new Set(['publish', 'login']),
309
- pnpm: new Set(['publish', 'login'])
310
- };
311
-
312
- function looksLikePath(value) {
313
- if (!value) return false;
314
- return value.includes('/') || value.includes('\\') || value.includes(':');
315
- }
316
-
317
- function resolveCommand(command) {
318
- if (!command || looksLikePath(command)) return command;
319
- if (RESOLVE_CACHE.has(command)) return RESOLVE_CACHE.get(command);
320
-
321
- let resolved = null;
322
- if (process.platform === 'win32') {
323
- const result = spawnSync('where', [command], { encoding: 'utf8' });
324
- if (result.status === 0) {
325
- const lines = String(result.stdout || '')
326
- .split(/\r?\n/)
327
- .map((value) => value.trim())
328
- .filter(Boolean);
329
- const preferred = lines.find((line) => PATHEXT.includes(path.extname(line).toLowerCase()));
330
- resolved = preferred || lines[0] || null;
331
- if (resolved && !path.extname(resolved)) {
332
- for (const ext of PATHEXT) {
333
- const candidate = `${resolved}${ext.toLowerCase()}`;
334
- if (fs.existsSync(candidate)) {
335
- resolved = candidate;
336
- break;
337
- }
338
- }
339
- }
340
- }
341
- } else {
342
- const result = spawnSync('which', [command], { encoding: 'utf8' });
343
- if (result.status === 0) {
344
- const line = String(result.stdout || '').trim();
345
- if (line) resolved = line;
346
- }
347
- }
348
-
349
- RESOLVE_CACHE.set(command, resolved || command);
350
- return resolved || command;
351
- }
352
-
353
- function normalizePowerShellGetPrefix(command) {
354
- if (!command) return command;
355
- const lowered = normalizeToken(command);
356
- if (!lowered.startsWith('get-')) return command;
357
- if (PATH_COMMANDS.has(command) || PATH_COMMANDS.has(lowered)) return command;
358
- const stripped = command.slice(4);
359
- if (!stripped) return command;
360
- if (PATH_COMMANDS.has(stripped)) return stripped;
361
- const match = findBestMatch(PATH_COMMANDS, stripped, MAX_DISTANCE);
362
- if (match) return stripped;
363
- return command;
364
- }
365
-
366
- function findBestMatch(candidates, target, maxDistance = MAX_DISTANCE) {
367
- if (!candidates || !target) return null;
368
- let best = null;
369
- let bestDistance = maxDistance + 1;
370
- let ties = [];
371
- for (const candidate of candidates || []) {
372
- const dist = damerauLevenshtein(candidate, target, maxDistance);
373
- if (dist < bestDistance) {
374
- best = candidate;
375
- bestDistance = dist;
376
- ties = [candidate];
377
- } else if (dist === bestDistance) {
378
- ties.push(candidate);
379
- }
380
- }
381
- if (!best || bestDistance > maxDistance) return null;
382
- if (ties.length > 1) {
383
- const preferred = ties.filter((value) => PRIORITY_BASES.has(normalizeToken(value)));
384
- if (preferred.length === 1) {
385
- return { match: preferred[0], distance: bestDistance };
386
- }
387
- return null;
388
- }
389
- return { match: best, distance: bestDistance };
390
- }
317
+ const PATH_COMMANDS = collectPathCommands();
318
+
319
+ function normalizePowerShellGetPrefix(command) {
320
+ if (!command) return command;
321
+ const lowered = normalizeToken(command);
322
+ if (!lowered.startsWith('get-')) return command;
323
+ if (PATH_COMMANDS.has(command) || PATH_COMMANDS.has(lowered)) return command;
324
+ const stripped = command.slice(4);
325
+ if (!stripped) return command;
326
+ if (PATH_COMMANDS.has(stripped)) return stripped;
327
+ const match = findBestMatch(PATH_COMMANDS, stripped, MAX_DISTANCE);
328
+ if (match) return stripped;
329
+ return command;
330
+ }
331
+
332
+ function findBestMatch(candidates, target, maxDistance = MAX_DISTANCE) {
333
+ if (!candidates || !target) return null;
334
+ let best = null;
335
+ let bestDistance = maxDistance + 1;
336
+ let ties = [];
337
+ for (const candidate of candidates || []) {
338
+ const dist = damerauLevenshtein(candidate, target, maxDistance);
339
+ if (dist < bestDistance) {
340
+ best = candidate;
341
+ bestDistance = dist;
342
+ ties = [candidate];
343
+ } else if (dist === bestDistance) {
344
+ ties.push(candidate);
345
+ }
346
+ }
347
+ if (!best || bestDistance > maxDistance) return null;
348
+ if (ties.length > 1) {
349
+ const preferred = ties.filter((value) => PRIORITY_BASES.has(normalizeToken(value)));
350
+ if (preferred.length === 1) {
351
+ return { match: preferred[0], distance: bestDistance };
352
+ }
353
+ return null;
354
+ }
355
+ return { match: best, distance: bestDistance };
356
+ }
391
357
 
392
358
  function parseSuggestion(text) {
393
359
  for (const pattern of suggestionPatterns) {
@@ -399,151 +365,134 @@ function parseSuggestion(text) {
399
365
  return null;
400
366
  }
401
367
 
402
- function run(cmd, args) {
403
- const interactive = isInteractiveCommand(cmd, args);
404
- const result = spawnSync(cmd, args, {
405
- encoding: 'utf8',
406
- stdio: interactive ? 'inherit' : ['inherit', 'pipe', 'pipe']
407
- });
408
- if (result.error && result.error.code === 'ENOENT') {
409
- const resolved = resolveCommand(cmd);
410
- if (resolved && resolved !== cmd) {
411
- const retryInteractive = isInteractiveCommand(resolved, args);
412
- const retry = spawnSync(resolved, args, {
413
- encoding: 'utf8',
414
- stdio: retryInteractive ? 'inherit' : ['inherit', 'pipe', 'pipe']
415
- });
416
- return {
417
- code: typeof retry.status === 'number' ? retry.status : retry.error ? 1 : 0,
418
- stdout: retryInteractive ? '' : retry.stdout || '',
419
- stderr: retryInteractive ? '' : retry.stderr || '',
420
- error: retry.error
421
- };
422
- }
423
- }
424
- return {
425
- code: typeof result.status === 'number' ? result.status : result.error ? 1 : 0,
426
- stdout: interactive ? '' : result.stdout || '',
427
- stderr: interactive ? '' : result.stderr || '',
428
- error: result.error
429
- };
430
- }
368
+ function run(cmd, args) {
369
+ const result = spawnSync(cmd, args, {
370
+ encoding: 'utf8',
371
+ stdio: ['inherit', 'pipe', 'pipe']
372
+ });
373
+ return {
374
+ code: typeof result.status === 'number' ? result.status : result.error ? 1 : 0,
375
+ stdout: result.stdout || '',
376
+ stderr: result.stderr || '',
377
+ error: result.error
378
+ };
379
+ }
380
+
381
+ function logFix(from, to) {
382
+ process.stderr.write(`fuzzrun: auto-correcting "${from}" -> "${to}"\n`);
383
+ }
384
+
385
+ function hasRiskyArgs(args) {
386
+ return args.some((arg) => RISKY_ARG_PATTERNS.some((pattern) => pattern.test(arg)));
387
+ }
388
+
389
+ function tryBaseCorrection(command, args) {
390
+ if (hasRiskyArgs(args)) return null;
391
+ const suggestion = findBestMatch(PATH_COMMANDS, command, MAX_DISTANCE);
392
+ if (suggestion && !DANGEROUS_BASE.has(suggestion.match) && suggestion.match !== command) {
393
+ logFix(command, suggestion.match);
394
+ return {
395
+ command: suggestion.match,
396
+ args,
397
+ result: run(suggestion.match, args)
398
+ };
399
+ }
400
+ return null;
401
+ }
402
+
403
+ function trySubcommandCorrection(command, args, combinedOutput) {
404
+ if (!SAFE_SUBCOMMAND_BASES.has(command) && !ALLOW_ANY_SUBCOMMANDS) return null;
405
+ if (!args.length) return null;
406
+ const attemptedSub = args[0];
407
+ if (attemptedSub.startsWith('-')) return null;
408
+ if (hasRiskyArgs(args)) return null;
409
+ const fromOutput = parseSuggestion(combinedOutput);
410
+ const candidates = COMMON_SUBCOMMANDS[command] || [];
411
+ const fromDict = findBestMatch(candidates, attemptedSub, MAX_DISTANCE);
412
+ const outputDistance = fromOutput
413
+ ? damerauLevenshtein(fromOutput, attemptedSub, MAX_DISTANCE)
414
+ : MAX_DISTANCE + 1;
415
+ const choice = outputDistance <= MAX_DISTANCE ? fromOutput : fromDict ? fromDict.match : null;
416
+
417
+ if (choice && choice !== attemptedSub && damerauLevenshtein(choice, attemptedSub, MAX_DISTANCE) <= MAX_DISTANCE) {
418
+ logFix(`${command} ${attemptedSub}`, `${command} ${choice}`);
419
+ return run(command, [choice, ...args.slice(1)]);
420
+ }
421
+ return null;
422
+ }
423
+
424
+ function findPackageJson(startDir) {
425
+ let current = startDir;
426
+ while (current && current !== path.dirname(current)) {
427
+ const candidate = path.join(current, 'package.json');
428
+ if (fs.existsSync(candidate)) return candidate;
429
+ current = path.dirname(current);
430
+ }
431
+ return null;
432
+ }
433
+
434
+ function getPackageScripts(cwd) {
435
+ const pkgPath = findPackageJson(cwd);
436
+ if (!pkgPath) return [];
437
+ try {
438
+ const raw = fs.readFileSync(pkgPath, 'utf8');
439
+ const parsed = JSON.parse(raw);
440
+ return Object.keys(parsed.scripts || {});
441
+ } catch (err) {
442
+ return [];
443
+ }
444
+ }
445
+
446
+ function isScriptError(output) {
447
+ return SCRIPT_ERROR_PATTERNS.some((pattern) => pattern.test(output));
448
+ }
449
+
450
+ function tryScriptCorrection(command, args, combinedOutput) {
451
+ if (!SCRIPT_BASES.has(command)) return null;
452
+ if (args.length < 2) return null;
453
+ if (args[0] !== 'run') return null;
454
+ const scriptName = args[1];
455
+ if (!scriptName || scriptName.startsWith('-')) return null;
456
+ if (!isScriptError(combinedOutput)) return null;
457
+ if (hasRiskyArgs(args)) return null;
458
+
459
+ const scripts = getPackageScripts(process.cwd());
460
+ const match = findBestMatch(scripts, scriptName, MAX_DISTANCE);
461
+ if (match) {
462
+ logFix(`${command} run ${scriptName}`, `${command} run ${match.match}`);
463
+ return run(command, ['run', match.match, ...args.slice(2)]);
464
+ }
465
+ return null;
466
+ }
467
+
468
+ function getGitBranches() {
469
+ const result = spawnSync('git', ['branch', '--format=%(refname:short)'], { encoding: 'utf8' });
470
+ if (result.status !== 0) return [];
471
+ return (result.stdout || '')
472
+ .split(/\r?\n/)
473
+ .map((line) => line.trim())
474
+ .filter(Boolean);
475
+ }
476
+
477
+ function tryGitBranchCorrection(command, args, combinedOutput) {
478
+ if (command !== 'git') return null;
479
+ if (args.length < 2) return null;
480
+ const subcommand = args[0];
481
+ if (subcommand !== 'checkout' && subcommand !== 'switch') return null;
482
+ const branch = args[1];
483
+ if (!branch || branch.startsWith('-')) return null;
484
+ if (!GIT_PATHSPEC_PATTERN.test(combinedOutput)) return null;
485
+ if (hasRiskyArgs(args)) return null;
486
+
487
+ const branches = getGitBranches();
488
+ const match = findBestMatch(branches, branch, MAX_DISTANCE);
489
+ if (match) {
490
+ logFix(`${command} ${subcommand} ${branch}`, `${command} ${subcommand} ${match.match}`);
491
+ return run(command, [subcommand, match.match, ...args.slice(2)]);
492
+ }
493
+ return null;
494
+ }
431
495
 
432
- function logFix(from, to) {
433
- process.stderr.write(`fuzzrun: auto-correcting "${from}" -> "${to}"\n`);
434
- }
435
-
436
- function hasRiskyArgs(args) {
437
- return args.some((arg) => RISKY_ARG_PATTERNS.some((pattern) => pattern.test(arg)));
438
- }
439
-
440
- function tryBaseCorrection(command, args) {
441
- if (hasRiskyArgs(args)) return null;
442
- const suggestion = findBestMatch(PATH_COMMANDS, command, MAX_DISTANCE);
443
- if (suggestion && !DANGEROUS_BASE.has(suggestion.match) && suggestion.match !== command) {
444
- logFix(command, suggestion.match);
445
- return {
446
- command: suggestion.match,
447
- args,
448
- result: run(suggestion.match, args)
449
- };
450
- }
451
- return null;
452
- }
453
-
454
- function trySubcommandCorrection(command, args, combinedOutput) {
455
- if (!SAFE_SUBCOMMAND_BASES.has(command) && !ALLOW_ANY_SUBCOMMANDS) return null;
456
- if (!args.length) return null;
457
- const attemptedSub = args[0];
458
- if (attemptedSub.startsWith('-')) return null;
459
- if (hasRiskyArgs(args)) return null;
460
- const fromOutput = parseSuggestion(combinedOutput);
461
- const candidates = COMMON_SUBCOMMANDS[command] || [];
462
- const fromDict = findBestMatch(candidates, attemptedSub, MAX_DISTANCE);
463
- const outputDistance = fromOutput
464
- ? damerauLevenshtein(fromOutput, attemptedSub, MAX_DISTANCE)
465
- : MAX_DISTANCE + 1;
466
- const choice = outputDistance <= MAX_DISTANCE ? fromOutput : fromDict ? fromDict.match : null;
467
-
468
- if (choice && choice !== attemptedSub && damerauLevenshtein(choice, attemptedSub, MAX_DISTANCE) <= MAX_DISTANCE) {
469
- logFix(`${command} ${attemptedSub}`, `${command} ${choice}`);
470
- return run(command, [choice, ...args.slice(1)]);
471
- }
472
- return null;
473
- }
474
-
475
- function findPackageJson(startDir) {
476
- let current = startDir;
477
- while (current && current !== path.dirname(current)) {
478
- const candidate = path.join(current, 'package.json');
479
- if (fs.existsSync(candidate)) return candidate;
480
- current = path.dirname(current);
481
- }
482
- return null;
483
- }
484
-
485
- function getPackageScripts(cwd) {
486
- const pkgPath = findPackageJson(cwd);
487
- if (!pkgPath) return [];
488
- try {
489
- const raw = fs.readFileSync(pkgPath, 'utf8');
490
- const parsed = JSON.parse(raw);
491
- return Object.keys(parsed.scripts || {});
492
- } catch (err) {
493
- return [];
494
- }
495
- }
496
-
497
- function isScriptError(output) {
498
- return SCRIPT_ERROR_PATTERNS.some((pattern) => pattern.test(output));
499
- }
500
-
501
- function tryScriptCorrection(command, args, combinedOutput) {
502
- if (!SCRIPT_BASES.has(command)) return null;
503
- if (args.length < 2) return null;
504
- if (args[0] !== 'run') return null;
505
- const scriptName = args[1];
506
- if (!scriptName || scriptName.startsWith('-')) return null;
507
- if (!isScriptError(combinedOutput)) return null;
508
- if (hasRiskyArgs(args)) return null;
509
-
510
- const scripts = getPackageScripts(process.cwd());
511
- const match = findBestMatch(scripts, scriptName, MAX_DISTANCE);
512
- if (match) {
513
- logFix(`${command} run ${scriptName}`, `${command} run ${match.match}`);
514
- return run(command, ['run', match.match, ...args.slice(2)]);
515
- }
516
- return null;
517
- }
518
-
519
- function getGitBranches() {
520
- const result = spawnSync('git', ['branch', '--format=%(refname:short)'], { encoding: 'utf8' });
521
- if (result.status !== 0) return [];
522
- return (result.stdout || '')
523
- .split(/\r?\n/)
524
- .map((line) => line.trim())
525
- .filter(Boolean);
526
- }
527
-
528
- function tryGitBranchCorrection(command, args, combinedOutput) {
529
- if (command !== 'git') return null;
530
- if (args.length < 2) return null;
531
- const subcommand = args[0];
532
- if (subcommand !== 'checkout' && subcommand !== 'switch') return null;
533
- const branch = args[1];
534
- if (!branch || branch.startsWith('-')) return null;
535
- if (!GIT_PATHSPEC_PATTERN.test(combinedOutput)) return null;
536
- if (hasRiskyArgs(args)) return null;
537
-
538
- const branches = getGitBranches();
539
- const match = findBestMatch(branches, branch, MAX_DISTANCE);
540
- if (match) {
541
- logFix(`${command} ${subcommand} ${branch}`, `${command} ${subcommand} ${match.match}`);
542
- return run(command, [subcommand, match.match, ...args.slice(2)]);
543
- }
544
- return null;
545
- }
546
-
547
496
  function main() {
548
497
  const argv = process.argv.slice(2);
549
498
  if (!argv.length) {
@@ -551,116 +500,118 @@ function main() {
551
500
  process.exit(1);
552
501
  }
553
502
 
554
- const action = argv[0];
555
- if (action === 'enable') {
556
- const results = installer.enable({});
557
- const updated = results.some((item) => item.updated);
558
- process.stdout.write(updated ? 'FuzzRun enabled. Restart your shell to apply changes.\n' : 'FuzzRun already enabled.\n');
559
- process.exit(0);
560
- }
561
- if (action === 'disable') {
562
- const results = installer.disable();
563
- const updated = results.some((item) => item.updated);
564
- process.stdout.write(updated ? 'FuzzRun disabled. Restart your shell to apply changes.\n' : 'FuzzRun already disabled.\n');
565
- process.exit(0);
566
- }
567
- if (action === 'status') {
568
- const results = installer.status();
569
- for (const item of results) {
570
- process.stdout.write(`${item.enabled ? 'enabled' : 'disabled'}: ${item.path}\n`);
571
- }
572
- process.exit(0);
573
- }
574
-
575
- if (process.env.FUZZRUN_SKIP_ENABLE !== '1') {
576
- try {
577
- const status = installer.status();
578
- const anyEnabled = status.some((item) => item.enabled);
579
- if (!anyEnabled) {
580
- const results = installer.enable({});
581
- const updated = results.some((item) => item.updated);
582
- if (updated) {
583
- process.stdout.write('FuzzRun auto-enabled. Restart your shell to apply changes.\n');
584
- }
585
- }
586
- } catch (err) {
587
- process.stderr.write(`fuzzrun: auto-enable failed: ${err.message}\n`);
588
- }
589
- }
503
+ showInstallBannerOnce();
590
504
 
591
- let baseCommand = argv[0];
592
- const rest = argv.slice(1);
593
- baseCommand = normalizePowerShellGetPrefix(baseCommand);
594
- const firstRun = run(baseCommand, rest);
595
-
596
- if (firstRun.error && firstRun.error.code === 'ENOENT') {
597
- const corrected = tryBaseCorrection(baseCommand, rest);
598
- if (corrected) {
599
- const { result } = corrected;
600
- if (result.code !== 0) {
601
- const combinedOutput = `${result.stderr}\n${result.stdout}`;
602
- const correctedSub = trySubcommandCorrection(corrected.command, corrected.args, combinedOutput);
603
- if (correctedSub) {
604
- process.stdout.write(correctedSub.stdout);
605
- process.stderr.write(correctedSub.stderr);
606
- process.exit(correctedSub.code);
607
- }
608
- const correctedScript = tryScriptCorrection(corrected.command, corrected.args, combinedOutput);
609
- if (correctedScript) {
610
- process.stdout.write(correctedScript.stdout);
611
- process.stderr.write(correctedScript.stderr);
612
- process.exit(correctedScript.code);
613
- }
614
- const correctedBranch = tryGitBranchCorrection(corrected.command, corrected.args, combinedOutput);
615
- if (correctedBranch) {
616
- process.stdout.write(correctedBranch.stdout);
617
- process.stderr.write(correctedBranch.stderr);
618
- process.exit(correctedBranch.code);
619
- }
620
- }
621
- process.stdout.write(result.stdout);
622
- process.stderr.write(result.stderr);
623
- process.exit(result.code);
624
- }
625
- process.stderr.write(firstRun.error.message ? `${firstRun.error.message}\n` : `fuzzrun: command not found: ${baseCommand}\n`);
626
- process.exit(firstRun.code);
627
- }
505
+ const action = argv[0];
506
+ if (action === 'enable') {
507
+ const results = installer.enable({});
508
+ const updated = results.some((item) => item.updated);
509
+ process.stdout.write(updated ? 'FuzzRun enabled. Restart your shell to apply changes.\n' : 'FuzzRun already enabled.\n');
510
+ process.exit(0);
511
+ }
512
+ if (action === 'disable') {
513
+ const results = installer.disable();
514
+ const updated = results.some((item) => item.updated);
515
+ process.stdout.write(updated ? 'FuzzRun disabled. Restart your shell to apply changes.\n' : 'FuzzRun already disabled.\n');
516
+ process.exit(0);
517
+ }
518
+ if (action === 'status') {
519
+ const results = installer.status();
520
+ for (const item of results) {
521
+ process.stdout.write(`${item.enabled ? 'enabled' : 'disabled'}: ${item.path}\n`);
522
+ }
523
+ process.exit(0);
524
+ }
628
525
 
629
- if (firstRun.code === 0) {
630
- process.stdout.write(firstRun.stdout);
631
- process.stderr.write(firstRun.stderr);
632
- process.exit(0);
633
- }
634
-
635
- const combinedOutput = `${firstRun.stderr}\n${firstRun.stdout}`;
636
- const correctedSub = trySubcommandCorrection(baseCommand, rest, combinedOutput);
637
- if (correctedSub) {
638
- process.stdout.write(correctedSub.stdout);
639
- process.stderr.write(correctedSub.stderr);
640
- process.exit(correctedSub.code);
641
- }
642
-
643
- const correctedScript = tryScriptCorrection(baseCommand, rest, combinedOutput);
644
- if (correctedScript) {
645
- process.stdout.write(correctedScript.stdout);
646
- process.stderr.write(correctedScript.stderr);
647
- process.exit(correctedScript.code);
648
- }
649
-
650
- const correctedBranch = tryGitBranchCorrection(baseCommand, rest, combinedOutput);
651
- if (correctedBranch) {
652
- process.stdout.write(correctedBranch.stdout);
653
- process.stderr.write(correctedBranch.stderr);
654
- process.exit(correctedBranch.code);
655
- }
656
-
657
- process.stdout.write(firstRun.stdout);
658
- process.stderr.write(firstRun.stderr);
659
- process.exit(firstRun.code);
660
- }
526
+ if (process.env.FUZZRUN_SKIP_ENABLE !== '1') {
527
+ try {
528
+ const status = installer.status();
529
+ const anyEnabled = status.some((item) => item.enabled);
530
+ if (!anyEnabled) {
531
+ const results = installer.enable({});
532
+ const updated = results.some((item) => item.updated);
533
+ if (updated) {
534
+ process.stdout.write('FuzzRun auto-enabled. Restart your shell to apply changes.\n');
535
+ }
536
+ }
537
+ } catch (err) {
538
+ process.stderr.write(`fuzzrun: auto-enable failed: ${err.message}\n`);
539
+ }
540
+ }
661
541
 
662
- if (require.main === module) {
663
- main();
664
- }
665
-
666
- module.exports = { main };
542
+ let baseCommand = argv[0];
543
+ const rest = argv.slice(1);
544
+ baseCommand = normalizePowerShellGetPrefix(baseCommand);
545
+ const firstRun = run(baseCommand, rest);
546
+
547
+ if (firstRun.error && firstRun.error.code === 'ENOENT') {
548
+ const corrected = tryBaseCorrection(baseCommand, rest);
549
+ if (corrected) {
550
+ const { result } = corrected;
551
+ if (result.code !== 0) {
552
+ const combinedOutput = `${result.stderr}\n${result.stdout}`;
553
+ const correctedSub = trySubcommandCorrection(corrected.command, corrected.args, combinedOutput);
554
+ if (correctedSub) {
555
+ process.stdout.write(correctedSub.stdout);
556
+ process.stderr.write(correctedSub.stderr);
557
+ process.exit(correctedSub.code);
558
+ }
559
+ const correctedScript = tryScriptCorrection(corrected.command, corrected.args, combinedOutput);
560
+ if (correctedScript) {
561
+ process.stdout.write(correctedScript.stdout);
562
+ process.stderr.write(correctedScript.stderr);
563
+ process.exit(correctedScript.code);
564
+ }
565
+ const correctedBranch = tryGitBranchCorrection(corrected.command, corrected.args, combinedOutput);
566
+ if (correctedBranch) {
567
+ process.stdout.write(correctedBranch.stdout);
568
+ process.stderr.write(correctedBranch.stderr);
569
+ process.exit(correctedBranch.code);
570
+ }
571
+ }
572
+ process.stdout.write(result.stdout);
573
+ process.stderr.write(result.stderr);
574
+ process.exit(result.code);
575
+ }
576
+ process.stderr.write(firstRun.error.message ? `${firstRun.error.message}\n` : `fuzzrun: command not found: ${baseCommand}\n`);
577
+ process.exit(firstRun.code);
578
+ }
579
+
580
+ if (firstRun.code === 0) {
581
+ process.stdout.write(firstRun.stdout);
582
+ process.stderr.write(firstRun.stderr);
583
+ process.exit(0);
584
+ }
585
+
586
+ const combinedOutput = `${firstRun.stderr}\n${firstRun.stdout}`;
587
+ const correctedSub = trySubcommandCorrection(baseCommand, rest, combinedOutput);
588
+ if (correctedSub) {
589
+ process.stdout.write(correctedSub.stdout);
590
+ process.stderr.write(correctedSub.stderr);
591
+ process.exit(correctedSub.code);
592
+ }
593
+
594
+ const correctedScript = tryScriptCorrection(baseCommand, rest, combinedOutput);
595
+ if (correctedScript) {
596
+ process.stdout.write(correctedScript.stdout);
597
+ process.stderr.write(correctedScript.stderr);
598
+ process.exit(correctedScript.code);
599
+ }
600
+
601
+ const correctedBranch = tryGitBranchCorrection(baseCommand, rest, combinedOutput);
602
+ if (correctedBranch) {
603
+ process.stdout.write(correctedBranch.stdout);
604
+ process.stderr.write(correctedBranch.stderr);
605
+ process.exit(correctedBranch.code);
606
+ }
607
+
608
+ process.stdout.write(firstRun.stdout);
609
+ process.stderr.write(firstRun.stderr);
610
+ process.exit(firstRun.code);
611
+ }
612
+
613
+ if (require.main === module) {
614
+ main();
615
+ }
616
+
617
+ module.exports = { main };