From ca4cb2a1449ca46723c7072d031dab2525bf1075 Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 16 Nov 2026 09:51:58 +0100 Subject: [PATCH] feat(qmd): switch to Qwen3 4B embedding and reranker models Use Qwen3-Embedding-4B and Qwen3-Reranker-4B (both Q4_K_M) for QMD local search, and make the switch reach existing installations: - Rewrite the setup-owned models block on every install and update, while still recording the user's original block only once. - When the new embedding size no longer matches stored vectors, the daemon clears the old vectors and re-embeds the repository. - Delete setup-downloaded model files the current models no longer use. - Skip npm and pnpm lockfiles and minified bundles when indexing repositories, which saves embedding work and removes search noise. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/configuration.md | 7 +++- scripts/lib/qmd.py | 35 +++++++++++++++++-- scripts/tests/test-qmd-daemon.mjs | 22 +++++++++++- scripts/tests/test-qmd-setup.py | 32 +++++++++++++++++ shared/qmd/qmd-daemon.mjs | 19 ++++++++-- shared/qmd/qmd-lib.mjs | 4 +-- .../skills/research/semantic-search/SKILL.md | 2 +- 8 files changed, 113 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 62f11fb..d60df43 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ Install and update also rebuild internally; the explicit build above lets you ch - User-level extension installation for Ponytail, i-have-adhd, Superpowers, Context7, Caveman, MCPorter, Humanizer, Impeccable, Anthropic Frontend Design, and REA, with an interactive extension toggle during both install and update. Only extensions installed and recorded by this setup can be removed through deselection. -- Optional local search for both clients through QMD with Qwen3-Embedding-0.6B, Qwen3-Reranker-0.6B, and QMD Query Expansion 1.7B (Yes/No/Auto; Auto benchmarks GPU, then CPU). +- Optional local search for both clients through QMD with Qwen3-Embedding-4B, Qwen3-Reranker-4B, and QMD Query Expansion 1.7B (Yes/No/Auto; Auto benchmarks GPU, then CPU). ## Requirements diff --git a/docs/configuration.md b/docs/configuration.md index 3e55950..b52642e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -79,8 +79,13 @@ Quickupdate reuses the saved choice and device; it does not rerun the benchmark. - **No:** omit the search skill and its instruction line, remove the warm-up hook registration, and disable search for the selected clients. Dry runs do not download, benchmark, or remove QMD resources. -The models are Qwen3-Embedding-0.6B, Qwen3-Reranker-0.6B, and QMD Query Expansion 1.7B. +The models are Qwen3-Embedding-4B, Qwen3-Reranker-4B, and QMD Query Expansion 1.7B. Exact model URIs live in [`shared/qmd/qmd-lib.mjs`](../shared/qmd/qmd-lib.mjs). +Install and update rewrite the setup-owned `models:` block, so changed models reach existing installations. +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. +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 100-document fixture; its measurements are not an end-to-end estimate for a user's repository. diff --git a/scripts/lib/qmd.py b/scripts/lib/qmd.py index 197355d..5be712b 100644 --- a/scripts/lib/qmd.py +++ b/scripts/lib/qmd.py @@ -59,6 +59,14 @@ def node_version_ok(text): return bool(match) and int(match.group(1)) >= 22 +def model_files(text): + """Cache file names node-llama-cpp gives the hf: model URIs in qmd-lib.mjs: hf__ plus .etag.""" + names = set() + for owner, file in re.findall(r"'hf:([^/']+)/[^/']+/([^/']+\.gguf)'", text): + names |= {f'hf_{owner}_{file}', f'{file}.etag'} + return names + + def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() @@ -176,8 +184,9 @@ class Setup: state['owned_package'] = True 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. + output = self.node('qmd-config.mjs', 'set-models') if not state['models_block']: - output = self.node('qmd-config.mjs', 'set-models') try: previous = json.loads(output.strip().splitlines()[-1])['previous'] except (IndexError, KeyError, TypeError, json.JSONDecodeError): @@ -190,6 +199,28 @@ class Setup: 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) + self.prune_models(state) + + def prune_models(self, state): + """Delete setup-downloaded model files the current models no longer use; foreign files stay.""" + current = model_files((self.root / 'shared' / 'qmd' / 'qmd-lib.mjs').read_text(encoding='utf-8')) + if not current: # an unparsable model list must never delete every model + return + kept = [] + for name in state['owned_models']: + if name in current: + kept.append(name) + continue + path = self.models / name + if name != Path(name).name or not path.is_file() or path.is_symlink(): + continue # already gone, or not a plain file the setup can safely delete + try: + path.unlink() + except OSError as error: # a running daemon may still hold it; the next update retries + print(f'QMD local search: could not delete unused model {name}: {error}', file=sys.stderr) + kept.append(name) + state['owned_models'] = sorted(kept) + atomic_json(self.state_path, state) def detect_gpu(self): try: @@ -205,7 +236,7 @@ class Setup: def enable(self, clients): state = self.load() if self.dry_run: - self.say('DRYRUN enable QMD local search: Qwen3-Embedding-0.6B, Qwen3-Reranker-0.6B, QMD query expansion 1.7B') + self.say('DRYRUN enable QMD local search: Qwen3-Embedding-4B, Qwen3-Reranker-4B, QMD query expansion 1.7B') return self.install(state) if state['device'] is None: diff --git a/scripts/tests/test-qmd-daemon.mjs b/scripts/tests/test-qmd-daemon.mjs index 7f2cb80..573779e 100644 --- a/scripts/tests/test-qmd-daemon.mjs +++ b/scripts/tests/test-qmd-daemon.mjs @@ -5,7 +5,7 @@ import { execFileSync } from 'node:child_process'; import { existsSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; -import { acquireStartLock, createServer, gitFingerprint, ignoreGlobs, keepModelsLoaded } from '../../shared/qmd/qmd-daemon.mjs'; +import { INDEX_EXCLUDES, acquireStartLock, createServer, gitFingerprint, ignoreGlobs, indexIgnores, keepModelsLoaded } from '../../shared/qmd/qmd-daemon.mjs'; import { collectionName } from '../../shared/qmd/qmd-lib.mjs'; const defaultHits = () => [{ displayPath: `${collectionName('/r')}/src/a.ts`, body: 'x\nretry here', bestChunkPos: 2, bestChunk: 'retry here', score: 0.91 }]; @@ -72,6 +72,19 @@ test('search adds the repo collection once, refreshes on change, and filters oth assert.equal(s.store.calls.filter((c) => c[0] === 'update').length, 1, 'unchanged fingerprint skips update'); }); +test('a changed embedding size clears old vectors and embeds again', async (t) => { + const s = await start(t); + let failures = 1; + const embed = s.store.embed; + s.store.embed = async (opts) => { + if (failures-- > 0) throw new Error('Embedding dimension mismatch: existing vectors are 1024d but the current model produces 2560d.'); + return embed(opts); + }; + s.store.internal = { clearAllEmbeddings: () => s.store.calls.push(['clear']) }; + assert.equal((await s.call('/search', { repo: '/r', query: 'q', limit: 1 })).status, 200); + assert.deepEqual(s.store.calls.filter((c) => c[0] === 'clear' || c[0] === 'embed').map((c) => c[0]), ['clear', 'embed']); +}); + test('rejects a missing query', async (t) => { const s = await start(t); assert.equal((await s.call('/search', { repo: '/r' })).status, 400); @@ -182,6 +195,13 @@ test('ignoreGlobs turns git ignored paths into escaped QMD ignore globs', () => assert.deepEqual(ignoreGlobs('', escape), []); }); +test('index ignores add lockfiles and minified bundles to the git ignored paths', () => { + const ignores = indexIgnores('/r', (path) => path, () => ['dist/**']); + assert.deepEqual(ignores, [...INDEX_EXCLUDES, 'dist/**']); + for (const pattern of ['**/package-lock.json', '**/pnpm-lock.yaml', '**/*.min.js']) assert.ok(ignores.includes(pattern)); + assert.deepEqual(indexIgnores('/r', (path) => path, () => []), INDEX_EXCLUDES, 'fixed excludes apply when git lists nothing'); +}); + test('git ignored paths reach addCollection and are persisted only when they change', async (t) => { let ignore = ['dist/**']; let fingerprint = 'one'; diff --git a/scripts/tests/test-qmd-setup.py b/scripts/tests/test-qmd-setup.py index 25069b1..2e617ce 100644 --- a/scripts/tests/test-qmd-setup.py +++ b/scripts/tests/test-qmd-setup.py @@ -103,6 +103,29 @@ 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_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) + self.assertIn('Qwen3-Embedding-4B-Q4_K_M.gguf.etag', names) + self.assertEqual(6, len(names)) + + def test_update_deletes_only_owned_models_no_longer_used(self): + models = self.home / '.cache/qmd/models' + current = qmd.model_files((ROOT / 'shared/qmd/qmd-lib.mjs').read_text(encoding='utf-8')) + create = lambda arguments: [(models / n).write_text('x') for n in current] if arguments[-1:] == ['pull'] else None + runner = FakeRunner(on_call=create) + self.setup(runner).enable(['claude']) + for name in ('hf_Qwen_Qwen3-Embedding-0.6B-Q8_0.gguf', 'foreign.gguf'): + (models / name).write_text('x') + state = self.state() + state['owned_models'].append('hf_Qwen_Qwen3-Embedding-0.6B-Q8_0.gguf') + (self.home / '.my-ai-configuration/qmd.json').write_text(json.dumps(state)) + self.setup(runner).enable(['claude']) + self.assertFalse((models / 'hf_Qwen_Qwen3-Embedding-0.6B-Q8_0.gguf').exists()) + self.assertTrue((models / 'foreign.gguf').exists()) + self.assertTrue(all((models / n).exists() for n in current)) + self.assertEqual(sorted(current), self.state()['owned_models']) + def test_disable_removes_owned_models_and_collections(self): runner = FakeRunner() setup = self.setup(runner) @@ -156,6 +179,15 @@ class SetupTest(unittest.TestCase): self.assertIn(['node', str(self.home / '.my-ai-configuration/qmd/qmd-config.mjs'), 'restore-models', '{"embed": "mine"}'], runner.calls) self.assertFalse(any(c[-1:] == ['unset-models'] for c in runner.calls)) + def test_update_rewrites_owned_models_block_and_keeps_user_original(self): + runner = FakeRunner(previous={'embed': 'mine'}) + self.setup(runner).enable(['claude']) + # The second run sees the setup's own older block; it must refresh it without recording it as the user's. + runner.previous = {'rerank': 'older setup default'} + self.setup(runner).enable(['claude']) + self.assertEqual(2, sum(c[-1:] == ['set-models'] for c in runner.calls)) + self.assertEqual(self.state()['previous_models'], {'embed': 'mine'}) + def test_models_block_removed_when_none_existed(self): runner = FakeRunner() setup = self.setup(runner) diff --git a/shared/qmd/qmd-daemon.mjs b/shared/qmd/qmd-daemon.mjs index 8685cab..c6c52dc 100644 --- a/shared/qmd/qmd-daemon.mjs +++ b/shared/qmd/qmd-daemon.mjs @@ -33,6 +33,13 @@ export function ignoreGlobs(output, escape) { return output.split('\0').filter(Boolean).map((path) => (path.endsWith('/') ? `${escape(path.slice(0, -1))}/**` : escape(path))); } +// Tracked lockfiles and minified bundles are large and generated: embedding them costs time and only adds noise to results. +export const INDEX_EXCLUDES = ['**/package-lock.json', '**/npm-shrinkwrap.json', '**/pnpm-lock.yaml', '**/*.min.js']; + +export function indexIgnores(repo, escape, git = gitIgnored) { + return [...INDEX_EXCLUDES, ...git(repo, escape)]; +} + export function gitIgnored(repo, escape) { try { return ignoreGlobs(execFileSync('git', ['-C', repo, 'ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory'], @@ -126,7 +133,15 @@ export function createServer({ store, token, idleMs, now = Date.now, onIdle, ext } } await store.update({ collections: [name] }); - await store.embed({ collection: name, chunkStrategy: 'auto' }); + try { + await store.embed({ collection: name, chunkStrategy: 'auto' }); + } catch (error) { + // QMD keeps one vector table, so a new embedding model with another size needs a full clear; other collections re-embed on their next refresh. + if (!/Embedding dimension mismatch/.test(error?.message ?? '')) throw error; + console.error('qmd-daemon: embedding model changed; clearing old vectors and re-embedding.'); + store.internal.clearAllEmbeddings(); + await store.embed({ collection: name, chunkStrategy: 'auto' }); + } fingerprints.set(name, fingerprint); return { collection: name, updated: true }; } @@ -223,7 +238,7 @@ async function main() { }; const daemon = createServer({ store, token, idleMs: idleMinutes() * 60_000, onIdle: stop, extractSnippet, - ignored: (repo) => gitIgnored(repo, fastGlob.escapePath), + ignored: (repo) => indexIgnores(repo, fastGlob.escapePath), persistIgnore: async (name, ignore) => { const path = qmdConfigPath(); const text = existsSync(path) ? readFileSync(path, 'utf8') : ''; diff --git a/shared/qmd/qmd-lib.mjs b/shared/qmd/qmd-lib.mjs index 9c6b7ec..bf2cf5c 100644 --- a/shared/qmd/qmd-lib.mjs +++ b/shared/qmd/qmd-lib.mjs @@ -8,8 +8,8 @@ import { dirname, join, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; export const MODELS = { - embed: 'hf:Qwen/Qwen3-Embedding-0.6B-GGUF/Qwen3-Embedding-0.6B-Q8_0.gguf', - rerank: 'hf:ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF/qwen3-reranker-0.6b-q8_0.gguf', + embed: 'hf:Qwen/Qwen3-Embedding-4B-GGUF/Qwen3-Embedding-4B-Q4_K_M.gguf', + rerank: 'hf:giladgd/Qwen3-Reranker-4B-GGUF/Qwen3-Reranker-4B.Q4_K_M.gguf', generate: 'hf:tobil/qmd-query-expansion-1.7B-gguf/qmd-query-expansion-1.7B-q4_k_m.gguf', }; export const MASK = '**/*.{md,py,cs,ts,tsx,js,jsx,mjs,go,rs,java,ps1,sh,json,yml,yaml,xml,sql}'; diff --git a/shared/skills/research/semantic-search/SKILL.md b/shared/skills/research/semantic-search/SKILL.md index 136a229..7440f45 100644 --- a/shared/skills/research/semantic-search/SKILL.md +++ b/shared/skills/research/semantic-search/SKILL.md @@ -5,7 +5,7 @@ description: MUST apply before open repository searches - run semantic retrieval # Semantic Search -Search the current Git repository, plus the user's registered QMD collections, by meaning. QMD runs locally with Qwen3-Embedding-0.6B, Qwen3-Reranker-0.6B, and QMD Query Expansion 1.7B; a background daemon keeps them loaded. +Search the current Git repository, plus the user's registered QMD collections, by meaning. QMD runs locally with Qwen3-Embedding-4B, Qwen3-Reranker-4B, and QMD Query Expansion 1.7B; a background daemon keeps them loaded. ## Rule