Swadhin Biswas feat: implement mervelas cli engine, built-in tools, and reactive UI · 4/3/2026
0358986
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
import { execa } from 'execa'
import { readFile, realpath } from 'fs/promises'
import { homedir } from 'os'
import { delimiter, join, posix, win32 } from 'path'
import { checkGlobalInstallPermissions } from './autoUpdater.js'
import { isInBundledMode } from './bundledMode.js'
import {
formatAutoUpdaterDisabledReason,
getAutoUpdaterDisabledReason,
getGlobalConfig,
type InstallMethod,
} from './config.js'
import { CLI_BINARY_NAME } from '../constants/product.js'
import { getCwd } from './cwd.js'
import { getClaudeConfigHomeDir, isEnvTruthy } from './envUtils.js'
import { execFileNoThrow } from './execFileNoThrow.js'
import { getFsImplementation } from './fsOperations.js'
import {
getShellType,
isRunningFromLocalInstallation,
localInstallationExists,
} from './localInstaller.js'
import {
detectApk,
detectAsdf,
detectDeb,
detectHomebrew,
detectMise,
detectPacman,
detectRpm,
detectWinget,
getPackageManager,
} from './nativeInstaller/packageManagers.js'
import { getPlatform } from './platform.js'
import { getRipgrepStatus } from './ripgrep.js'
import { SandboxManager } from './sandbox/sandbox-adapter.js'
import { getManagedFilePath } from './settings/managedPath.js'
import { CUSTOMIZATION_SURFACES } from './settings/types.js'
import {
findClaudeAlias,
findValidClaudeAlias,
getShellConfigPaths,
} from './shellConfig.js'
import { jsonParse } from './slowOperations.js'
import { which } from './which.js'
export type InstallationType =
| 'npm-global'
| 'npm-local'
| 'native'
| 'package-manager'
| 'development'
| 'unknown'
export type DiagnosticInfo = {
installationType: InstallationType
version: string
installationPath: string
invokedBinary: string
configInstallMethod: InstallMethod | 'not set'
autoUpdates: string
hasUpdatePermissions: boolean | null
multipleInstallations: Array<{ type: string; path: string }>
warnings: Array<{ issue: string; fix: string }>
recommendation?: string
packageManager?: string
ripgrepStatus: {
working: boolean
mode: 'system' | 'builtin' | 'embedded'
systemPath: string | null
}
}
function getNormalizedPaths(): [invokedPath: string, execPath: string] {
let invokedPath = process.argv[1] || ''
let execPath = process.execPath || process.argv[0] || ''
// On Windows, convert backslashes to forward slashes for consistent path matching
if (getPlatform() === 'windows') {
invokedPath = invokedPath.split(win32.sep).join(posix.sep)
execPath = execPath.split(win32.sep).join(posix.sep)
}
return [invokedPath, execPath]
}
export async function getCurrentInstallationType(): Promise<InstallationType> {
if (process.env.NODE_ENV === 'development') {
return 'development'
}
const [invokedPath] = getNormalizedPaths()
// Check if running in bundled mode first
if (isInBundledMode()) {
// Check if this bundled instance was installed by a package manager
if (
detectHomebrew() ||
detectWinget() ||
detectMise() ||
detectAsdf() ||
(await detectPacman()) ||
(await detectDeb()) ||
(await detectRpm()) ||
(await detectApk())
) {
return 'package-manager'
}
return 'native'
}
// Check if running from local npm installation
if (isRunningFromLocalInstallation()) {
return 'npm-local'
}
// Check if we're in a typical npm global location
const npmGlobalPaths = [
'/usr/local/lib/node_modules',
'/usr/lib/node_modules',
'/opt/homebrew/lib/node_modules',
'/opt/homebrew/bin',
'/usr/local/bin',
'/.nvm/versions/node/', // nvm installations
]
if (npmGlobalPaths.some(path => invokedPath.includes(path))) {
return 'npm-global'
}
// Also check for npm/nvm in the path even if not in standard locations
if (invokedPath.includes('/npm/') || invokedPath.includes('/nvm/')) {
return 'npm-global'
}
const npmConfigResult = await execa('npm config get prefix', {
shell: true,
reject: false,
})
const globalPrefix =
npmConfigResult.exitCode === 0 ? npmConfigResult.stdout.trim() : null
if (globalPrefix && invokedPath.startsWith(globalPrefix)) {
return 'npm-global'
}
// If we can't determine, return unknown
return 'unknown'
}
async function getInstallationPath(): Promise<string> {
if (process.env.NODE_ENV === 'development') {
return getCwd()
}
// For bundled/native builds, show the binary location
if (isInBundledMode()) {
// Try to find the actual binary that was invoked
try {
return await realpath(process.execPath)
} catch {
// This function doesn't expect errors
}
try {
const path = await which(CLI_BINARY_NAME)
if (path) {
return path
}
} catch {
// This function doesn't expect errors
}
// If we can't find it, check common locations
try {
await getFsImplementation().stat(
join(homedir(), '.local/bin', CLI_BINARY_NAME),
)
return join(homedir(), '.local/bin', CLI_BINARY_NAME)
} catch {
// Not found
}
return 'native'
}
// For npm installations, use the path of the executable
try {
return process.argv[0] || 'unknown'
} catch {
return 'unknown'
}
}
export function getInvokedBinary(): string {
try {
// For bundled/compiled executables, show the actual binary path
if (isInBundledMode()) {
return process.execPath || 'unknown'
}
// For npm/development, show the script path
return process.argv[1] || 'unknown'
} catch {
return 'unknown'
}
}
async function detectMultipleInstallations(): Promise<
Array<{ type: string; path: string }>
> {
const fs = getFsImplementation()
const installations: Array<{ type: string; path: string }> = []
// Check for local installation
const localPath = join(getClaudeConfigHomeDir(), 'local')
if (await localInstallationExists()) {
installations.push({ type: 'npm-local', path: localPath })
}
// Check for global npm installation
const packagesToCheck = ['@anthropic-ai/claude-code']
if (MACRO.PACKAGE_URL && MACRO.PACKAGE_URL !== '@anthropic-ai/claude-code') {
packagesToCheck.push(MACRO.PACKAGE_URL)
}
const npmResult = await execFileNoThrow('npm', [
'-g',
'config',
'get',
'prefix',
])
if (npmResult.code === 0 && npmResult.stdout) {
const npmPrefix = npmResult.stdout.trim()
const isWindows = getPlatform() === 'windows'
// First check for active installations via bin/claude
// Linux / macOS have prefix/bin/claude and prefix/lib/node_modules
// Windows has prefix/claude and prefix/node_modules
const globalBinPath = isWindows
? join(npmPrefix, 'claude')
: join(npmPrefix, 'bin', 'claude')
let globalBinExists = false
try {
await fs.stat(globalBinPath)
globalBinExists = true
} catch {
// Not found
}
if (globalBinExists) {
// Check if this is actually a Homebrew cask installation, not npm-global
// When npm is installed via Homebrew, both can exist at /opt/homebrew/bin/claude
// We need to resolve the symlink to see where it actually points
let isCurrentHomebrewInstallation = false
try {
// Resolve the symlink to get the actual target
const realPath = await realpath(globalBinPath)
// If the symlink points to a Caskroom directory, it's a Homebrew cask
// Only skip it if it's the same Homebrew installation we're currently running from
if (realPath.includes('/Caskroom/')) {
isCurrentHomebrewInstallation = detectHomebrew()
}
} catch {
// If we can't resolve the symlink, include it anyway
}
if (!isCurrentHomebrewInstallation) {
installations.push({ type: 'npm-global', path: globalBinPath })
}
} else {
// If no bin/claude exists, check for orphaned packages (no bin/claude symlink)
for (const packageName of packagesToCheck) {
const globalPackagePath = isWindows
? join(npmPrefix, 'node_modules', packageName)
: join(npmPrefix, 'lib', 'node_modules', packageName)
try {
await fs.stat(globalPackagePath)
installations.push({
type: 'npm-global-orphan',
path: globalPackagePath,
})
} catch {
// Package not found
}
}
}
}
// Check for native installation
// Check common native installation paths
const nativeBinPath = join(homedir(), '.local', 'bin', 'claude')
try {
await fs.stat(nativeBinPath)
installations.push({ type: 'native', path: nativeBinPath })
} catch {
// Not found
}
// Also check if config indicates native installation
const config = getGlobalConfig()
if (config.installMethod === 'native') {
const nativeDataPath = join(homedir(), '.local', 'share', 'claude')
try {
await fs.stat(nativeDataPath)
if (!installations.some(i => i.type === 'native')) {
installations.push({ type: 'native', path: nativeDataPath })
}
} catch {
// Not found
}
}
return installations
}
async function detectConfigurationIssues(
type: InstallationType,
): Promise<Array<{ issue: string; fix: string }>> {
const warnings: Array<{ issue: string; fix: string }> = []
// Managed-settings forwards-compat: the schema preprocess silently drops
// unknown strictPluginOnlyCustomization surface names so one future enum
// value doesn't null out the entire policy file (settings.ts:101). But
// admins should KNOW — read the raw file and diff. Runs before the
// development-mode early return: this is config correctness, not an
// install-path check, and it's useful to see during dev testing.
try {
const raw = await readFile(
join(getManagedFilePath(), 'managed-settings.json'),
'utf-8',
)
const parsed: unknown = jsonParse(raw)
const field =
parsed && typeof parsed === 'object'
? (parsed as Record<string, unknown>).strictPluginOnlyCustomization
: undefined
if (field !== undefined && typeof field !== 'boolean') {
if (!Array.isArray(field)) {
// .catch(undefined) in the schema silently drops this, so the rest
// of managed settings survive — but the admin typed something
// wrong (an object, a string, etc.).
warnings.push({
issue: `managed-settings.json: strictPluginOnlyCustomization has an invalid value (expected true or an array, got ${typeof field})`,
fix: `The field is silently ignored (schema .catch rescues it). Set it to true, or an array of: ${CUSTOMIZATION_SURFACES.join(', ')}.`,
})
} else {
const unknown = field.filter(
x =>
typeof x === 'string' &&
!(CUSTOMIZATION_SURFACES as readonly string[]).includes(x),
)
if (unknown.length > 0) {
warnings.push({
issue: `managed-settings.json: strictPluginOnlyCustomization has ${unknown.length} value(s) this client doesn't recognize: ${unknown.map(String).join(', ')}`,
fix: `These are silently ignored (forwards-compat). Known surfaces for this version: ${CUSTOMIZATION_SURFACES.join(', ')}. Either remove them, or this client is older than the managed-settings intended.`,
})
}
}
}
} catch {
// ENOENT (no managed settings) / parse error — not this check's concern.
// Parse errors are surfaced by the settings loader itself.
}
const config = getGlobalConfig()
// Skip most warnings for development mode
if (type === 'development') {
return warnings
}
// Check if ~/.local/bin is in PATH for native installations
if (type === 'native') {
const path = process.env.PATH || ''
const pathDirectories = path.split(delimiter)
const homeDir = homedir()
const localBinPath = join(homeDir, '.local', 'bin')
// On Windows, convert backslashes to forward slashes for consistent path matching
let normalizedLocalBinPath = localBinPath
if (getPlatform() === 'windows') {
normalizedLocalBinPath = localBinPath.split(win32.sep).join(posix.sep)
}
// Check if ~/.local/bin is in PATH (handle both expanded and unexpanded forms)
// Also handle trailing slashes that users may have in their PATH
const localBinInPath = pathDirectories.some(dir => {
let normalizedDir = dir
if (getPlatform() === 'windows') {
normalizedDir = dir.split(win32.sep).join(posix.sep)
}
// Remove trailing slashes for comparison (handles paths like /home/user/.local/bin/)
const trimmedDir = normalizedDir.replace(/\/+$/, '')
const trimmedRawDir = dir.replace(/[/\\]+$/, '')
return (
trimmedDir === normalizedLocalBinPath ||
trimmedRawDir === '~/.local/bin' ||
trimmedRawDir === '$HOME/.local/bin'
)
})
if (!localBinInPath) {
const isWindows = getPlatform() === 'windows'
if (isWindows) {
// Windows-specific PATH instructions
const windowsLocalBinPath = localBinPath
.split(posix.sep)
.join(win32.sep)
warnings.push({
issue: `Native installation exists but ${windowsLocalBinPath} is not in your PATH`,
fix: `Add it by opening: System Properties → Environment Variables → Edit User PATH → New → Add the path above. Then restart your terminal.`,
})
} else {
// Unix-style PATH instructions
const shellType = getShellType()
const configPaths = getShellConfigPaths()
const configFile = configPaths[shellType as keyof typeof configPaths]
const displayPath = configFile
? configFile.replace(homedir(), '~')
: 'your shell config file'
warnings.push({
issue:
'Native installation exists but ~/.local/bin is not in your PATH',
fix: `Run: echo 'export PATH="$HOME/.local/bin:$PATH"' >> ${displayPath} then open a new terminal or run: source ${displayPath}`,
})
}
}
}
// Check for configuration mismatches
// Skip these checks if DISABLE_INSTALLATION_CHECKS is set (e.g., in HFI)
if (!isEnvTruthy(process.env.DISABLE_INSTALLATION_CHECKS)) {
if (type === 'npm-local' && config.installMethod !== 'local') {
warnings.push({
issue: `Running from local installation but config install method is '${config.installMethod}'`,
fix: 'Consider using native installation: mervelas install',
})
}
if (type === 'native' && config.installMethod !== 'native') {
warnings.push({
issue: `Running native installation but config install method is '${config.installMethod}'`,
fix: 'Run mervelas install to update configuration',
})
}
}
if (type === 'npm-global' && (await localInstallationExists())) {
warnings.push({
issue: 'Local installation exists but not being used',
fix: 'Consider using native installation: mervelas install',
})
}
const existingAlias = await findClaudeAlias()
const validAlias = await findValidClaudeAlias()
// Check if running local installation but it's not in PATH
if (type === 'npm-local') {
// Check if claude is already accessible via PATH
const whichResult = await which('claude')
const claudeInPath = !!whichResult
// Only show warning if claude is NOT in PATH AND no valid alias exists
if (!claudeInPath && !validAlias) {
if (existingAlias) {
// Alias exists but points to invalid target
warnings.push({
issue: 'Local installation not accessible',
fix: `Alias exists but points to invalid target: ${existingAlias}. Update alias: alias mervelas="~/.mervelas/local/mervelas"`,
})
} else {
// No alias exists and not in PATH
warnings.push({
issue: 'Local installation not accessible',
fix: 'Create alias: alias mervelas="~/.mervelas/local/mervelas"',
})
}
}
}
return warnings
}
export function detectLinuxGlobPatternWarnings(): Array<{
issue: string
fix: string
}> {
if (getPlatform() !== 'linux') {
return []
}
const warnings: Array<{ issue: string; fix: string }> = []
const globPatterns = SandboxManager.getLinuxGlobPatternWarnings()
if (globPatterns.length > 0) {
// Show first 3 patterns, then indicate if there are more
const displayPatterns = globPatterns.slice(0, 3).join(', ')
const remaining = globPatterns.length - 3
const patternList =
remaining > 0 ? `${displayPatterns} (${remaining} more)` : displayPatterns
warnings.push({
issue: `Glob patterns in sandbox permission rules are not fully supported on Linux`,
fix: `Found ${globPatterns.length} pattern(s): ${patternList}. On Linux, glob patterns in Edit/Read rules will be ignored.`,
})
}
return warnings
}
export async function getDoctorDiagnostic(): Promise<DiagnosticInfo> {
const installationType = await getCurrentInstallationType()
const version =
typeof MACRO !== 'undefined' && MACRO.VERSION ? MACRO.VERSION : 'unknown'
const installationPath = await getInstallationPath()
const invokedBinary = getInvokedBinary()
const multipleInstallations = await detectMultipleInstallations()
const warnings = await detectConfigurationIssues(installationType)
// Add glob pattern warnings for Linux sandboxing
warnings.push(...detectLinuxGlobPatternWarnings())
// Add warnings for leftover npm installations when running native
if (installationType === 'native') {
const npmInstalls = multipleInstallations.filter(
i =>
i.type === 'npm-global' ||
i.type === 'npm-global-orphan' ||
i.type === 'npm-local',
)
const isWindows = getPlatform() === 'windows'
for (const install of npmInstalls) {
if (install.type === 'npm-global') {
let uninstallCmd = 'npm -g uninstall @anthropic-ai/claude-code'
if (
MACRO.PACKAGE_URL &&
MACRO.PACKAGE_URL !== '@anthropic-ai/claude-code'
) {
uninstallCmd += ` && npm -g uninstall ${MACRO.PACKAGE_URL}`
}
warnings.push({
issue: `Leftover npm global installation at ${install.path}`,
fix: `Run: ${uninstallCmd}`,
})
} else if (install.type === 'npm-global-orphan') {
warnings.push({
issue: `Orphaned npm global package at ${install.path}`,
fix: isWindows
? `Run: rmdir /s /q "${install.path}"`
: `Run: rm -rf ${install.path}`,
})
} else if (install.type === 'npm-local') {
warnings.push({
issue: `Leftover npm local installation at ${install.path}`,
fix: isWindows
? `Run: rmdir /s /q "${install.path}"`
: `Run: rm -rf ${install.path}`,
})
}
}
}
const config = getGlobalConfig()
// Get config values for display
const configInstallMethod = config.installMethod || 'not set'
// Check permissions for global installations
let hasUpdatePermissions: boolean | null = null
if (installationType === 'npm-global') {
const permCheck = await checkGlobalInstallPermissions()
hasUpdatePermissions = permCheck.hasPermissions
// Add warning if no permissions
if (!hasUpdatePermissions && !getAutoUpdaterDisabledReason()) {
warnings.push({
issue: 'Insufficient permissions for auto-updates',
fix: 'Do one of: (1) Re-install node without sudo, or (2) Use `mervelas install` for native installation',
})
}
}
// Get ripgrep status and configuration
const ripgrepStatusRaw = getRipgrepStatus()
// Provide simple ripgrep status info
const ripgrepStatus = {
working: ripgrepStatusRaw.working ?? true, // Assume working if not yet tested
mode: ripgrepStatusRaw.mode,
systemPath:
ripgrepStatusRaw.mode === 'system' ? ripgrepStatusRaw.path : null,
}
// Get package manager info if running from package manager
const packageManager =
installationType === 'package-manager'
? await getPackageManager()
: undefined
const diagnostic: DiagnosticInfo = {
installationType,
version,
installationPath,
invokedBinary,
configInstallMethod,
autoUpdates: (() => {
const reason = getAutoUpdaterDisabledReason()
return reason
? `disabled (${formatAutoUpdaterDisabledReason(reason)})`
: 'enabled'
})(),
hasUpdatePermissions,
multipleInstallations,
warnings,
packageManager,
ripgrepStatus,
}
return diagnostic
}