Compare commits

..
2 Commits
Author SHA1 Message Date
Julian LechnerandClaude Opus 5.5 6fad45105f fix(qmd): run global npm CLIs without relying on PATH
CI / CI configuration security checks (push) Successful in 2s
CI / Capabilities and shell quality (push) Successful in 12s
CI / Python tests and compilation (push) Successful in 25s
CI / QMD unit tests (push) Successful in 5s
CI / Build and inspect generated packages (push) Successful in 15s
CI / PowerShell tests on Ubuntu (push) Successful in 1m5s
CI / Installed client configuration smoke tests (push) Successful in 40s
CI / Bash integration and installation guards (push) Successful in 1m10s
npm's global bin directory is often missing from PATH on Windows, so the
installer failed at `qmd pull` right after installing the package. Run the
QMD CLI through node from `npm root --global`, as the QMD scripts already
do, and look up other globally installed CLIs such as mcporter in
`npm prefix --global` when they are not on PATH. Doctor now warns when
npm's global bin directory is missing from PATH, since agents call
mcporter directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 11:24:10 +01:00
Julian LechnerandClaude Opus 5.5 a89be2604b fix(qmd): treat a missing global npm prefix as not installed
On a machine where no global npm package was ever installed, the global
prefix directory does not exist and `npm list --global --json` reports
ENOENT without a dependency list. QMD setup treated that as an unreliable
listing and failed the install/update. It now means the package is not
installed; other unreliable listings still fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 11:08:51 +01:00
7 changed files with 111 additions and 7 deletions

No files matched your search

+2 -1
View File
@@ -107,7 +107,8 @@ Install and update also rebuild internally; the explicit build above lets you ch
- Bash 4.3 or newer, with standard utilities such as `awk`, `sed`, and `sha256sum`.
- Python 3.11 or newer for configuration validation and the Python-based hooks and helpers. Scripts and hooks try `python`, `python3`, and the `py -3` launcher (Bash: `python3` first) and use the first one that actually runs Python 3.11+, so the Windows Store app execution alias is ignored. Without Python, build and capability checks stop with an actionable message, doctor reports a failure, and the registered Python-based hooks are skipped.
- `jq` for Claude's Bash status line; without it, that status line produces no output.
- Node.js 22 or newer and `npm` when local QMD search or MCPorter is selected.
- Node.js 22 or newer and `npm` when local QMD search or MCPorter is selected. npm's global bin directory (`npm prefix --global`; on Windows usually `%APPDATA%
pm`) must be on `PATH` so agents can call `mcporter`; `doctor` warns when it is missing.
Core Bash setup scripts do not require PowerShell. The credential commands use Windows Credential Manager and require
PowerShell, including when invoked through their Bash wrappers. The PowerShell scripts remain compatible with
+10
View File
@@ -38,6 +38,16 @@ foreach ($tool in @('codex','claude')) {
} else { Result 'WARN' "$tool unavailable" }
}
if (Get-Command jq -ErrorAction SilentlyContinue) { Result 'PASS' 'jq available for Claude Bash status line' } else { Result 'WARN' 'jq unavailable; Claude Bash status line is disabled' }
# Globally installed npm CLIs (qmd, mcporter) must be callable by agents, so npm's global bin directory belongs on PATH.
if (Get-Command npm -ErrorAction SilentlyContinue) {
$npmPrefix = @((Invoke-DoctorCommand -Command 'npm' -Arguments @('prefix', '--global')).Output | ForEach-Object { "$_".Trim() } | Where-Object { $_ }) | Select-Object -Last 1
if ($npmPrefix) {
$npmBin = if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { $npmPrefix } else { Join-Path $npmPrefix 'bin' }
$pathEntries = @($env:PATH -split [regex]::Escape([string][System.IO.Path]::PathSeparator) | ForEach-Object { $_.TrimEnd([char[]]@('\', '/')) })
if ($pathEntries -contains $npmBin.TrimEnd([char[]]@('\', '/'))) { Result 'PASS' "npm global bin directory is on PATH ($npmBin)" }
else { Result 'WARN' "npm global bin directory $npmBin is not on PATH; agents cannot call globally installed CLIs such as mcporter. Add it to your user PATH and restart the terminal." }
}
}
$python = Get-PythonCommand
if ($python) { Result 'PASS' "Python available ($($python.Display))" }
else { Result 'FAIL' "$(Get-PythonMissingMessage) Without it, build validation fails and the completion-evidence, correction-prompt, and session-state hooks are silently skipped." }
+14
View File
@@ -36,6 +36,20 @@ for tool in codex claude; do
else result WARN "$tool unavailable"; fi
done
command -v jq >/dev/null && result PASS 'jq available for Claude Bash status line' || result WARN 'jq unavailable; Claude Bash status line is disabled'
# Globally installed npm CLIs (qmd, mcporter) must be callable by agents, so npm's global bin directory belongs on PATH.
if command -v npm >/dev/null 2>&1; then
npm_prefix=$(npm prefix --global 2>/dev/null | tr -d '␍' | tail -n 1)
if [ -n "$npm_prefix" ]; then
case "$(uname -s 2>/dev/null)" in
MINGW*|MSYS*|CYGWIN*) npm_bin=$(cygpath -u "$npm_prefix" 2>/dev/null || printf '%s' "$npm_prefix") ;;
*) npm_bin="$npm_prefix/bin" ;;
esac
case ":$PATH:" in
*":$npm_bin:"*|*":$npm_bin/:"*) result PASS "npm global bin directory is on PATH ($npm_bin)" ;;
*) result WARN "npm global bin directory $npm_bin is not on PATH; agents cannot call globally installed CLIs such as mcporter. Add it to your user PATH and restart the terminal." ;;
esac
fi
fi
if resolve_python; then
result PASS "Python available ($(python_display))"
else
+20 -1
View File
@@ -55,8 +55,27 @@ def atomic_write(path, data):
temporary.unlink(missing_ok=True)
def find_executable(name):
found = shutil.which(name)
if found or name == 'npm':
return found
# npm's global bin directory is often missing from PATH right after a Node.js setup on Windows,
# so a CLI this setup just installed globally (such as mcporter) would not be found otherwise.
npm = shutil.which('npm')
if npm is None:
return None
try:
prefix = subprocess.run([npm, 'prefix', '--global'], stdin=subprocess.DEVNULL, capture_output=True,
text=True, timeout=60).stdout.strip()
except (OSError, subprocess.SubprocessError):
return None
if not prefix:
return None
return shutil.which(name, path=prefix if os.name == 'nt' else os.path.join(prefix, 'bin'))
def run_command(arguments, summary=False, home=None):
executable = shutil.which(arguments[0])
executable = find_executable(arguments[0])
if executable is None:
raise ValueError(f'{arguments[0]} CLI is required to manage plugins.')
environment = os.environ.copy()
+14 -3
View File
@@ -20,7 +20,7 @@ WINDOWS = os.name == 'nt'
def run(arguments, env=None, timeout=1800, check=True):
result = subprocess.run(arguments, env=env, capture_output=True, text=True, encoding='utf-8', errors='replace',
timeout=timeout, shell=WINDOWS and arguments[0] in ('npm', 'qmd'))
timeout=timeout, shell=WINDOWS and arguments[0] == 'npm')
if check and result.returncode != 0:
raise ValueError(f'{" ".join(arguments[:3])} failed: {(result.stderr or result.stdout).strip()[-300:]}')
return result.stdout
@@ -94,6 +94,12 @@ class Setup:
def node(self, script, *arguments, env=None, timeout=1800):
return self.run(['node', str(self.scripts / script), *arguments], env=env, timeout=timeout)
def qmd_cli(self, *arguments, timeout=1800):
# Run the CLI through node from the global package, as qmd-lib.mjs does, so it also works
# when npm's global bin directory is not on PATH (common on Windows right after install).
package = os.environ.get('QMD_PACKAGE_DIR') or str(Path(self.run(['npm', 'root', '--global']).strip()) / '@tobilu' / 'qmd')
return self.run(['node', str(Path(package) / 'dist' / 'cli' / 'qmd.js'), *arguments], timeout=timeout)
def package_installed(self):
# npm list exits non-zero on tree problems (ELSPROBLEMS) but still prints valid JSON.
output = self.run(['npm', 'list', '--global', '--depth=0', '--json'], check=False)
@@ -101,6 +107,11 @@ class Setup:
listing = json.loads(output)
except json.JSONDecodeError:
raise ValueError('npm list did not return JSON.')
# Before the first global install the global prefix directory does not exist; npm then
# reports ENOENT without a dependency list, which means nothing is installed yet.
error = listing.get('error') if isinstance(listing, dict) else None
if isinstance(error, dict) and error.get('code') == 'ENOENT' and 'dependencies' not in listing:
return False
if not isinstance(listing, dict) or not isinstance(listing.get('dependencies'), dict):
raise ValueError('npm list did not report the global packages.')
return PACKAGE in listing['dependencies']
@@ -175,7 +186,7 @@ class Setup:
state['models_block'] = True
atomic_json(self.state_path, state)
before = {p.name for p in self.models.iterdir()} if self.models.is_dir() else set()
self.run(['qmd', 'pull'], timeout=3600)
self.qmd_cli('pull', timeout=3600)
after = {p.name for p in self.models.iterdir()} if self.models.is_dir() else set()
state['owned_models'] = sorted(set(state['owned_models']) | (after - before))
atomic_json(self.state_path, state)
@@ -223,7 +234,7 @@ class Setup:
for name in names:
if re.fullmatch(r'repo-[0-9a-f]{12}', name):
try:
self.run(['qmd', 'collection', 'remove', name])
self.qmd_cli('collection', 'remove', name)
except (ValueError, subprocess.SubprocessError):
pass
if state['models_block'] and self.scripts.joinpath('qmd-config.mjs').exists():
+25
View File
@@ -336,6 +336,31 @@ class CommandTests(unittest.TestCase):
result = extensions.run_command([str(executable), 'plugin', 'list', '--json'], True, home)
self.assertEqual([str(home / '.codex'), str(home / '.claude')], result.splitlines())
def test_global_npm_cli_is_found_when_its_directory_is_not_on_path(self):
with tempfile.TemporaryDirectory() as temporary:
prefix = Path(temporary)
bin_dir = prefix if os.name == 'nt' else prefix / 'bin'
bin_dir.mkdir(exist_ok=True)
tool = bin_dir / ('mcporter.cmd' if os.name == 'nt' else 'mcporter')
tool.write_text('@echo off\n' if os.name == 'nt' else '#!/bin/sh\n')
tool.chmod(0o700)
real_which = shutil.which
def which(name, mode=os.F_OK | os.X_OK, path=None):
if path is None:
return '/usr/bin/npm' if name == 'npm' else None
return real_which(name, mode, path)
prefix_result = subprocess.CompletedProcess(['npm'], 0, stdout=f'{prefix}\n', stderr='')
with patch.object(extensions.shutil, 'which', side_effect=which), \
patch.object(extensions.subprocess, 'run', return_value=prefix_result):
found = extensions.find_executable('mcporter')
self.assertEqual(Path(found).resolve(), tool.resolve())
def test_missing_cli_stays_missing_without_npm(self):
with patch.object(extensions.shutil, 'which', return_value=None):
self.assertIsNone(extensions.find_executable('mcporter'))
if __name__ == '__main__':
unittest.main()
+26 -2
View File
@@ -34,7 +34,7 @@ class FakeRunner:
return self.node
if arguments[-1:] == ['set-models']:
return json.dumps({'previous': self.previous}) + chr(10)
if self.fail_pull and arguments[:2] == ['qmd', 'pull']:
if self.fail_pull and arguments[0] == 'node' and arguments[-1:] == ['pull']:
raise ValueError('pull failed')
if 'npm list' in joined and self.list_output is not None:
return self.list_output
@@ -115,7 +115,8 @@ class SetupTest(unittest.TestCase):
(self.home / '.my-ai-configuration/qmd/collections.json').write_text(json.dumps(['repo-abcdefabcdef']))
setup.disable(['claude'])
self.assertFalse(model.exists())
self.assertIn(['qmd', 'collection', 'remove', 'repo-abcdefabcdef'], runner.calls)
self.assertTrue(any(call[0] == 'node' and call[1].endswith('qmd.js') and call[2:] == ['collection', 'remove', 'repo-abcdefabcdef']
for call in runner.calls), runner.calls)
self.assertIn(['npm', 'uninstall', '--global', '@tobilu/qmd'], runner.calls)
def test_benchmark_unsuitable_cleans_up(self):
@@ -220,6 +221,29 @@ class SetupTest(unittest.TestCase):
self.assertTrue(self.setup(FakeRunner(list_output='{"dependencies": {"@tobilu/qmd": {}}, "error": {}}')).package_installed())
self.assertFalse(self.setup(FakeRunner(list_output='{"dependencies": {}}')).package_installed())
def test_qmd_cli_runs_through_node_without_relying_on_path(self):
# npm's global bin directory is often missing from PATH on Windows right after install.
runner = FakeRunner()
runner_root = str(self.home / 'npm-root')
original = runner.__call__
def call(arguments, env=None, timeout=None, check=True):
if arguments == ['npm', 'root', '--global']:
runner.calls.append(list(arguments))
return runner_root + '\n'
return original(arguments, env=env, timeout=timeout, check=check)
setup = self.setup(call)
setup.qmd_cli('pull')
expected = str(Path(runner_root) / '@tobilu' / 'qmd' / 'dist' / 'cli' / 'qmd.js')
self.assertIn(['node', expected, 'pull'], runner.calls)
self.assertFalse(any(call[0] == 'qmd' for call in runner.calls))
def test_package_installed_treats_missing_global_prefix_as_not_installed(self):
# npm reports ENOENT for the global prefix before anything was ever installed globally.
output = '{"error": {"code": "ENOENT", "summary": "ENOENT: no such file or directory, lstat \'C:\\\\Users\\\\me\\\\AppData\\\\Roaming\\\\npm\'"}}'
self.assertFalse(self.setup(FakeRunner(list_output=output)).package_installed())
def test_non_mapping_previous_models_are_restored_verbatim(self):
runner = FakeRunner(previous='custom.gguf')
setup = self.setup(runner)