From 6fad45105fdeb755fc831b2cdfedc26a33a6e113 Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Thu, 5 Nov 2026 11:24:10 +0100 Subject: [PATCH] fix(qmd): run global npm CLIs without relying on PATH 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 --- README.md | 3 ++- scripts/commands/doctor.ps1 | 10 ++++++++++ scripts/commands/doctor.sh | 14 +++++++++++++ scripts/lib/managed-extensions.py | 21 +++++++++++++++++++- scripts/lib/qmd.py | 12 +++++++++--- scripts/tests/test-managed-extensions.py | 25 ++++++++++++++++++++++++ scripts/tests/test-qmd-setup.py | 23 ++++++++++++++++++++-- 7 files changed, 101 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index e680121..e4606fd 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/scripts/commands/doctor.ps1 b/scripts/commands/doctor.ps1 index 86c0d7c..f6a781d 100644 --- a/scripts/commands/doctor.ps1 +++ b/scripts/commands/doctor.ps1 @@ -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." } diff --git a/scripts/commands/doctor.sh b/scripts/commands/doctor.sh index d6c3499..448c952 100644 --- a/scripts/commands/doctor.sh +++ b/scripts/commands/doctor.sh @@ -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 diff --git a/scripts/lib/managed-extensions.py b/scripts/lib/managed-extensions.py index e6bc734..4388a41 100644 --- a/scripts/lib/managed-extensions.py +++ b/scripts/lib/managed-extensions.py @@ -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() diff --git a/scripts/lib/qmd.py b/scripts/lib/qmd.py index 7d6a4f1..197355d 100644 --- a/scripts/lib/qmd.py +++ b/scripts/lib/qmd.py @@ -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) @@ -180,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) @@ -228,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(): diff --git a/scripts/tests/test-managed-extensions.py b/scripts/tests/test-managed-extensions.py index fe29d2d..bfc12ce 100644 --- a/scripts/tests/test-managed-extensions.py +++ b/scripts/tests/test-managed-extensions.py @@ -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() diff --git a/scripts/tests/test-qmd-setup.py b/scripts/tests/test-qmd-setup.py index fa911f5..25069b1 100644 --- a/scripts/tests/test-qmd-setup.py +++ b/scripts/tests/test-qmd-setup.py @@ -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,24 @@ 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\'"}}'