From 82d9992b3aa74351d0ed6f3641ca58b856f91fe6 Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 16 Nov 2026 09:58:48 +0100 Subject: [PATCH] fix(qmd): restart daemon on update, check version, add doctor checks - Stop the running QMD daemon before install and update replace the runtime scripts, so the next search loads the new code and models and Windows no longer keeps old model files locked. - Read the installed @tobilu/qmd version: reinstall a setup-owned package at the tested version, and warn about a foreign one of another version. - Add QMD checks to doctor (PowerShell and Bash) through `qmd.py doctor`: runtime script digests, package version, model files, and daemon health. Co-Authored-By: Claude Opus 5.5 --- docs/configuration.md | 3 + scripts/commands/doctor.ps1 | 6 ++ scripts/commands/doctor.sh | 10 ++++ scripts/lib/qmd.py | 101 ++++++++++++++++++++++++++------ scripts/tests/test-qmd-setup.py | 43 ++++++++++++-- 5 files changed, 141 insertions(+), 22 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index b52642e..0360dfb 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -85,6 +85,9 @@ Install and update rewrite the setup-owned `models:` block, so changed models re When a new embedding model produces vectors of another size, the daemon clears all old vectors and re-embeds each repository on its next search; run `qmd embed` to re-embed your own QMD collections. Install and update also delete model files the setup downloaded that the current models no longer use. +They stop a running QMD daemon first, so the next search uses the new scripts and models. A QMD package +the setup installed is reinstalled at the tested version; a foreign installation of another version is kept +and reported. `doctor` checks the runtime scripts, the QMD version, the model files, and the daemon. Repository indexes skip git-ignored files, npm and pnpm lockfiles, and minified `*.min.js` bundles. Auto thresholds can be overridden with `QMD_BENCHMARK_MAX_QUERY_SECONDS` and `QMD_BENCHMARK_MIN_CHUNKS_PER_SECOND`. The benchmark uses a temporary database and a deterministic diff --git a/scripts/commands/doctor.ps1 b/scripts/commands/doctor.ps1 index f6a781d..9c0e673 100644 --- a/scripts/commands/doctor.ps1 +++ b/scripts/commands/doctor.ps1 @@ -51,6 +51,12 @@ if (Get-Command npm -ErrorAction SilentlyContinue) { $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." } +# QMD local search: reports nothing when the setup did not enable it. +if ($python) { + $qmdChecks = Invoke-DoctorCommand -Command $python.Path -Arguments (@($python.Arguments) + @((Join-Path $root 'scripts/lib/qmd.py'), 'doctor', '--root', $root, '--home', $homePath)) + if ($qmdChecks.ExitCode -ne 0) { Result 'WARN' "QMD checks failed: $($qmdChecks.Output -join ' ')" } + else { foreach ($line in $qmdChecks.Output) { if ("$line" -match '^(PASS|WARN|FAIL) (.+)$') { Result $Matches[1] $Matches[2] } } } +} $sourceAgentCount = @(Get-ChildItem (Join-Path $root 'shared/agents') -Directory -ErrorAction SilentlyContinue).Count $sourceSkillCount = @(Get-ChildItem (Join-Path $root 'shared/skills') -Filter 'SKILL.md' -Recurse -ErrorAction SilentlyContinue).Count diff --git a/scripts/commands/doctor.sh b/scripts/commands/doctor.sh index 448c952..b9cf4a3 100644 --- a/scripts/commands/doctor.sh +++ b/scripts/commands/doctor.sh @@ -55,6 +55,16 @@ if resolve_python; then else result FAIL "$(python_missing_message) Without it, build validation fails and the completion-evidence, correction-prompt, and session-state hooks are silently skipped." fi +# QMD local search: reports nothing when the setup did not enable it. +if resolve_python; then + if qmd_output=$(run_python "$root/scripts/lib/qmd.py" doctor --root "$root" --home "$home_path" 2>&1); then + while IFS= read -r line; do + case "$line" in PASS\ *|WARN\ *|FAIL\ *) result "${line%% *}" "${line#* }" ;; esac + done <<< "$qmd_output" + else + result WARN "QMD checks failed: ${qmd_output//$'\n'/ }" + fi +fi source_agent_count=$(find "$root/shared/agents" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l) source_skill_count=$(find "$root/shared/skills" -name SKILL.md | wc -l) diff --git a/scripts/lib/qmd.py b/scripts/lib/qmd.py index 5be712b..d85c9fd 100644 --- a/scripts/lib/qmd.py +++ b/scripts/lib/qmd.py @@ -10,6 +10,7 @@ import subprocess import sys import tempfile import time +import urllib.request PACKAGE = '@tobilu/qmd' VERSION = '2.8.3' @@ -109,6 +110,10 @@ class Setup: return self.run(['node', str(Path(package) / 'dist' / 'cli' / 'qmd.js'), *arguments], timeout=timeout) def package_installed(self): + return self.package_version() is not None + + def package_version(self): + """Installed global QMD version, '' when npm lists it without one, or None when it is absent.""" # 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) try: @@ -119,10 +124,30 @@ class Setup: # 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 + return None 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'] + entry = listing['dependencies'].get(PACKAGE) + if entry is None: + return None + return str(entry.get('version') or '') if isinstance(entry, dict) else '' + + def stop_daemon(self): + """Stop the setup's QMD daemon and wait until it releases the scripts, models, and package.""" + daemon = self.scripts / 'daemon.json' + try: + pid = json.loads(daemon.read_text(encoding='utf-8')).get('pid') if daemon.is_file() else None + except (OSError, ValueError, AttributeError): + pid = None + try: + if self.scripts.joinpath('qmd-search.mjs').exists(): + self.node('qmd-search.mjs', '--stop', timeout=60) + except (ValueError, OSError, subprocess.SubprocessError): + pass + if isinstance(pid, int) and pid > 0: + deadline = time.monotonic() + 10 + while process_alive(pid) and time.monotonic() < deadline: + time.sleep(0.2) def require_node(self): if not node_version_ok(self.run(['node', '--version'])): @@ -179,9 +204,16 @@ class Setup: """Steps shared by Yes and Auto: package, scripts, models block, model download.""" self.require_node() self.migrate(state) - if not self.package_installed(): + # A running daemon keeps old code and models loaded and locks the model files on Windows. + self.stop_daemon() + version = self.package_version() + if version is None or (state['owned_package'] and version != VERSION): self.run(['npm', 'install', '--global', f'{PACKAGE}@{VERSION}']) state['owned_package'] = True + elif version != VERSION: + # A foreign installation is never changed; the runtime scripts rely on internals of the tested version. + print(f'QMD local search: the installed {PACKAGE} {version or "(unknown version)"} is not the tested {VERSION}; ' + f'search may fall back to the slower CLI. Run: npm install --global {PACKAGE}@{VERSION}', file=sys.stderr) self.install_scripts(state) atomic_json(self.state_path, state) # Rewrite the setup-owned block on every run so changed default models reach existing installs. @@ -246,20 +278,7 @@ class Setup: self.say(f'QMD local search enabled on {state["device"].upper()}.') def remove_all(self, state): - daemon = self.scripts / 'daemon.json' - try: - pid = json.loads(daemon.read_text(encoding='utf-8')).get('pid') if daemon.is_file() else None - except (OSError, ValueError, AttributeError): - pid = None - try: - if self.scripts.joinpath('qmd-search.mjs').exists(): - self.node('qmd-search.mjs', '--stop', timeout=60) - except (ValueError, OSError, subprocess.SubprocessError): - pass - if isinstance(pid, int) and pid > 0: - deadline = time.monotonic() + 10 # the daemon must release the model files and the package - while process_alive(pid) and time.monotonic() < deadline: - time.sleep(0.2) + self.stop_daemon() collections = self.scripts / 'collections.json' names = json.loads(collections.read_text(encoding='utf-8')) if collections.exists() else [] for name in names: @@ -356,9 +375,51 @@ class Setup: return True +def doctor_checks(setup): + """Read-only QMD checks for the doctor command, as (PASS|WARN|FAIL, message) pairs; none when QMD is not set up.""" + if not setup.state_path.exists(): + return [] + state = setup.load() + checks = [] + scripts = {name: setup.scripts / name for name in state['files']} + missing = sorted(name for name, path in scripts.items() if not path.is_file()) + changed = sorted(name for name, path in scripts.items() if path.is_file() and digest(path) != state['files'][name]) + checks.append(('FAIL', f'QMD runtime scripts are missing: {", ".join(missing)}') if missing + else ('WARN', f'QMD runtime scripts were modified: {", ".join(changed)}') if changed + else ('PASS', 'QMD runtime scripts match the setup')) + try: + version = setup.package_version() + checks.append(('FAIL', f'{PACKAGE} is not installed') if version is None + else ('PASS', f'{PACKAGE} {version} installed') if version == VERSION + else ('WARN', f'{PACKAGE} {version or "(unknown version)"} is not the tested {VERSION}; search may fall back to the slower CLI')) + except (ValueError, OSError, subprocess.SubprocessError) as error: + checks.append(('WARN', f'could not read the {PACKAGE} version: {error}')) + library = setup.scripts / 'qmd-lib.mjs' + wanted = sorted(n for n in model_files(library.read_text(encoding='utf-8') if library.is_file() else '') if n.endswith('.gguf')) + absent = [n for n in wanted if not (setup.models / n).is_file()] + checks.append(('WARN', f'QMD model files are not downloaded yet: {", ".join(absent)}') if absent + else ('PASS', f'QMD model files present ({len(wanted)})')) + info = None + try: + info = json.loads((setup.scripts / 'daemon.json').read_text(encoding='utf-8')) + except (OSError, ValueError): + pass + if isinstance(info, dict) and info.get('port') and info.get('token'): + request = urllib.request.Request(f'http://127.0.0.1:{int(info["port"])}/health', headers={'x-qmd-token': str(info['token'])}) + try: + with urllib.request.urlopen(request, timeout=2) as response: + running = json.loads(response.read().decode('utf-8')).get('service') == 'ai-config-qmd' + except (OSError, ValueError): + running = False + checks.append(('PASS', 'QMD daemon answers') if running else ('WARN', 'QMD daemon.json is stale; the next search starts a new daemon')) + else: + checks.append(('PASS', 'QMD daemon is not running; the next search starts it')) + return checks + + def main(): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('action', choices=('sync', 'benchmark')) + parser.add_argument('action', choices=('sync', 'benchmark', 'doctor')) parser.add_argument('--root', required=True, type=Path) parser.add_argument('--home', required=True, type=Path) parser.add_argument('--client', choices=('codex', 'claude', 'both')) @@ -370,6 +431,10 @@ def main(): setup = Setup(args.home.resolve(), args.root.resolve(), run, args.dry_run, args.summary) if args.action == 'benchmark': raise SystemExit(0 if setup.benchmark() else 2) + if args.action == 'doctor': + for status, message in doctor_checks(setup): + print(f'{status} {message}') + return if args.client is None or args.enabled is None: parser.error('sync requires --client and --enabled') clients = ['codex', 'claude'] if args.client == 'both' else [args.client] diff --git a/scripts/tests/test-qmd-setup.py b/scripts/tests/test-qmd-setup.py index 2e617ce..1534506 100644 --- a/scripts/tests/test-qmd-setup.py +++ b/scripts/tests/test-qmd-setup.py @@ -1,4 +1,5 @@ import importlib.util +import io import json import os from pathlib import Path @@ -17,8 +18,8 @@ spec.loader.exec_module(qmd) class FakeRunner: def __init__(self, installed=False, gpu='cuda', gpu_result=None, cpu_result=None, previous=None, fail_pull=False, list_output=None, - node='v22.4.0', fail=(), on_call=None): - self.calls, self.installed, self.gpu = [], installed, gpu + node='v22.4.0', fail=(), on_call=None, version='2.8.3'): + self.calls, self.installed, self.gpu, self.version = [], installed, gpu, version self.previous, self.fail_pull, self.list_output = previous, fail_pull, list_output self.node, self.fail, self.on_call = node, fail, on_call self.results = {'gpu': gpu_result, 'cpu': cpu_result} @@ -39,9 +40,9 @@ class FakeRunner: if 'npm list' in joined and self.list_output is not None: return self.list_output if 'npm list' in joined: - return json.dumps({'dependencies': {'@tobilu/qmd': {}} if self.installed else {}}) + return json.dumps({'dependencies': {'@tobilu/qmd': {'version': self.version}} if self.installed else {}}) if 'npm install' in joined: - self.installed = True + self.installed, self.version = True, arguments[-1].rsplit('@', 1)[-1] if 'npm uninstall' in joined: self.installed = False if '--detect' in joined: @@ -103,6 +104,40 @@ class SetupTest(unittest.TestCase): self.assertFalse(any('npm uninstall' in ' '.join(c) for c in runner.calls)) self.assertFalse((self.home / '.my-ai-configuration/qmd.json').exists()) + def test_update_stops_the_running_daemon_before_replacing_scripts(self): + runner = FakeRunner() + self.setup(runner).enable(['claude']) + runner.calls.clear() + self.setup(runner).enable(['claude']) + stop = next(i for i, c in enumerate(runner.calls) if c[-1:] == ['--stop']) + set_models = next(i for i, c in enumerate(runner.calls) if c[-1:] == ['set-models']) + self.assertLess(stop, set_models) + + def test_owned_package_with_another_version_is_reinstalled(self): + runner = FakeRunner() + self.setup(runner).enable(['claude']) + runner.version = '2.7.0' + runner.calls.clear() + self.setup(runner).enable(['claude']) + self.assertIn(['npm', 'install', '--global', '@tobilu/qmd@2.8.3'], runner.calls) + + def test_foreign_package_with_another_version_only_warns(self): + runner = FakeRunner(installed=True, version='2.9.0') + with mock.patch('sys.stderr', new_callable=io.StringIO) as stderr: + self.setup(runner).enable(['claude']) + self.assertFalse(any('npm install' in ' '.join(c) for c in runner.calls)) + self.assertIn('2.9.0 is not the tested 2.8.3', stderr.getvalue()) + + def test_doctor_checks_report_scripts_package_models_and_daemon(self): + setup = self.setup(FakeRunner()) + self.assertEqual([], qmd.doctor_checks(setup)) + setup.enable(['claude']) + checks = qmd.doctor_checks(setup) + # Scripts match, package matches, models not downloaded in the fake runner, daemon not running. + self.assertEqual(['PASS', 'PASS', 'WARN', 'PASS'], [status for status, _ in checks], checks) + (self.home / '.my-ai-configuration/qmd/qmd-search.mjs').write_text('changed') + self.assertEqual(('WARN', 'QMD runtime scripts were modified: qmd-search.mjs'), qmd.doctor_checks(setup)[0]) + def test_model_files_follow_node_llama_cpp_cache_names(self): names = qmd.model_files((ROOT / 'shared/qmd/qmd-lib.mjs').read_text(encoding='utf-8')) self.assertIn('hf_Qwen_Qwen3-Embedding-4B-Q4_K_M.gguf', names)