Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

fix: the qmd search path was paying for a duplicate vector search and inheriting the wrong embedder (#251)

Brenno Ferrari01b56c45d6d1
diff --git a/.claude/scripts/lib/mcp-qmd-client.ts b/.claude/scripts/lib/mcp-qmd-client.ts
index 35cca76..4fcea16 100644
--- a/.claude/scripts/lib/mcp-qmd-client.ts
+++ b/.claude/scripts/lib/mcp-qmd-client.ts
@@ -65,9 +65,6 @@ export function vaultRelKey(vaultRoot: string, fullPath: string): string {
return p.startsWith(v) ? p.slice(v.length).replace(/^\/+/, "") : p;
}
-/** A word that marks a query as a question rather than a set of keywords. */
-const QUESTION_SHAPED = /\b(why|how|what|when|where|which|who|should|can|does|did|is|are|was)\b|\?/i;
-
export interface SubQuery {
readonly type: "lex" | "vec" | "hyde";
readonly query: string;
@@ -76,23 +73,34 @@ export interface SubQuery {
/**
* Build the typed sub-queries for one search.
*
- * `lex` and `vec` always go out together: keywords find the exact term, vectors
- * find the note that answers the question without using the word.
+ * `lex` and `vec` go out together and are the whole of it: keywords find the
+ * exact term, vectors find the note that answers the question without using the
+ * word.
+ *
+ * There is deliberately no `hyde` sub-query. qmd treats `hyde` as a LABEL on a
+ * vector search rather than as a mode — as of 2.8.3 every site in its store
+ * reads `type === 'vec' || type === 'hyde'`, and generation happens only inside
+ * `expandQuery()`, which the plain-text `query` parameter reaches and a
+ * `searches` array bypasses. A `hyde` sub-query carrying the raw question is
+ * therefore byte-for-byte the `vec` search already in this list, issued twice.
+ *
+ * Measured before removing it, over 211 human-labelled pairs: sending it never,
+ * conditionally, or always produced identical rank-1 and found@5 to four
+ * decimal places, changing 0 of 211 top hits on the better embedder and 2 on
+ * the worse, for +35-40ms per query. The comment this replaces asserted that it
+ * "runs a local generation model", and that belief is what kept the cost
+ * looking justified.
*
- * `hyde` is added only for question-shaped queries. It writes a hypothetical
- * answer and matches against that, which is what helps when someone asks "why
- * did we decide X" and the note is titled something else entirely. It is not
- * free — it runs a local generation model — so a two-word keyword lookup, where
- * lexical matching is already the right tool, does not pay for it.
+ * An authored `hyde` — a caller-written passage describing what the answer
+ * would look like — is a real technique, and `SubQuery` still allows the type.
+ * Handing it the user's question is not that.
*/
export function subQueries(query: string): SubQuery[] {
const q = String(query).trim();
- const subs: SubQuery[] = [
+ return [
{ type: "lex", query: q },
{ type: "vec", query: q },
];
- if (q.split(/\s+/).length >= 4 && QUESTION_SHAPED.test(q)) subs.push({ type: "hyde", query: q });
- return subs;
}
/** qmd paths are collection-prefixed: `myvault/brain/Foo.md` → `brain/foo.md`. */
diff --git a/.claude/scripts/lib/qmd-models.ts b/.claude/scripts/lib/qmd-models.ts
new file mode 100644
index 0000000..094b762
--- /dev/null
+++ b/.claude/scripts/lib/qmd-models.ts
@@ -0,0 +1,240 @@
+/**
+ * Which embedding model this vault's qmd index uses, and how that choice is
+ * written into qmd's YAML config without disturbing anything else in it.
+ *
+ * qmd picks its embedder as `config.embed || QMD_EMBED_MODEL || <its default>`,
+ * and — this is the part that decides the shape here — it MATERIALISES its
+ * defaults into the config file the first time it touches an index. So the
+ * environment variable is only ever read before that first write, which for a
+ * template means never reliably. The config file is the only durable surface.
+ *
+ * qmd owns that file and rewrites it as collections change, so editing it is
+ * expected rather than intrusive. The edit is still surgical: it touches one
+ * key and leaves collections, patterns, ignore lists and the context string
+ * exactly as they were.
+ */
+
+import { readFileSync, writeFileSync } from "node:fs";
+
+import { warn } from "./hook-io.ts";
+
+/**
+ * qmd's own default embedder, as of 2.8.3. Recognised so the upsert can tell
+ * "nobody chose this" from "somebody chose this" — the first is ours to
+ * replace, the second is not.
+ */
+export const QMD_DEFAULT_EMBED_MODEL =
+ "hf:ggml-org/embeddinggemma-300M-GGUF/embeddinggemma-300M-Q8_0.gguf";
+
+/**
+ * Every embedder qmd has shipped as its default, not just the current one.
+ *
+ * The failure this exists for is silent in both directions. qmd materialises
+ * its default into the config on first use, so when a future version ships a
+ * different one it lands in configs unasked — and matching only the current
+ * default would then read that as somebody's deliberate choice and stop
+ * applying this template's embedder, with no error and no failing test. Worse,
+ * the `warn()` below goes to stderr, and the SessionStart self-heal spawns the
+ * bootstrap with stdio ignored, so nothing surfaces anywhere.
+ *
+ * Add to this set rather than replacing: a config still holding an older qmd
+ * default is exactly as unchosen as one holding the current one.
+ */
+const QMD_SHIPPED_DEFAULTS: ReadonlySet<string> = new Set([
+ // The only one so far: verified identical in 2.1.0, 2.5.3 and 2.8.3.
+ QMD_DEFAULT_EMBED_MODEL,
+]);
+
+/**
+ * What this template uses instead.
+ *
+ * Measured on a 684-document vault against 211 human-labelled retrieval pairs,
+ * with the query path otherwise untouched: rank-1 0.299 → 0.469 and found@5
+ * 0.521 → 0.758, McNemar exact p < 0.0001 over 66 discordant pairs. Replicated
+ * on a second, independently written vault at rank-1 0.650 → 0.950 (p =
+ * 0.0003), which is what distinguishes an embedder that suits vaults from one
+ * that happened to suit the first corpus tried.
+ *
+ * It costs ~13ms a query and roughly doubles a full index build. Reranking is
+ * NOT the cheaper substitute: on the default embedder reranking is a large
+ * significant gain, on this one it is not significant on rank-1 (p = 0.185) —
+ * it had been compensating for the embedder — and this model without a
+ * reranker beats the default model with one at an eighth of the latency.
+ */
+export const PREFERRED_EMBED_MODEL =
+ "hf:Qwen/Qwen3-Embedding-0.6B-GGUF/Qwen3-Embedding-0.6B-Q8_0.gguf";
+
+/**
+ * A `models:` key in any spelling at all. Used to decide whether appending a
+ * block is safe — never to locate one for editing.
+ */
+const MODELS_KEY_RE = /^models:/m;
+
+/**
+ * The block-style `models:` mapping, which is the only shape this can edit: the
+ * header (with an optional trailing comment) plus every following line that is
+ * indented or blank.
+ */
+const MODELS_BLOCK_RE = /^models:[ \t]*(?:#[^\n]*)?\n(?:(?![^\s]).*\n?)*/m;
+
+/**
+ * An `embed:` entry inside that block. The value is captured loosely — empty,
+ * quoted and comment-suffixed values all match — because failing to match here
+ * means inserting a SECOND `embed:` key, which is a corrupt file rather than a
+ * missed improvement.
+ */
+const EMBED_LINE_RE = /^([ \t]+)embed:[ \t]*(.*?)[ \t]*$/m;
+
+/**
+ * Reduce a captured YAML scalar to the string it denotes: drop an inline
+ * comment, then one layer of surrounding quotes.
+ *
+ * Without this, `embed: "<qmd's default>"` and `embed: <qmd's default> # note`
+ * both compare unequal to the default and get classified as somebody's
+ * deliberate choice — so the vault silently keeps the worse embedder and is
+ * told its model is "neither qmd's default nor this template's" when it is
+ * exactly qmd's default.
+ */
+function yamlScalar(raw: string): string {
+ let v = raw.trim();
+ const comment = v.search(/\s#/);
+ if (comment !== -1) v = v.slice(0, comment).trim();
+ const quoted =
+ (v.startsWith('"') && v.endsWith('"')) ||
+ (v.startsWith("'") && v.endsWith("'"));
+ return quoted && v.length >= 2 ? v.slice(1, -1) : v;
+}
+
+/**
+ * The outcome of trying to set `models.embed`. Three of the four produce no
+ * write, and they are kept distinct because they need different handling:
+ *
+ * - `updated` — the key was absent or still held qmd's default, and `content`
+ * is the file to write. Existing vectors are now the wrong dimension, so the
+ * caller MUST force a re-embed; qmd raises a hard error otherwise, and a
+ * query in that state throws rather than degrading.
+ * - `already-set` — nothing to do, so re-running is free.
+ * - `user-chosen` — somebody set a different model deliberately. Never
+ * overwritten: a template supplies a better default, it does not overrule a
+ * choice.
+ * - `unsupported` — there is a `models:` key this cannot edit safely (flow
+ * style, say). Refusing is the whole point: the alternative is appending a
+ * second `models:` key, and a duplicate key makes the file unparseable, which
+ * takes qmd's collections and all search down with it.
+ */
+export type EmbedModelPatch =
+ | { readonly kind: "updated"; readonly content: string }
+ | { readonly kind: "already-set" }
+ | { readonly kind: "user-chosen"; readonly current: string }
+ | { readonly kind: "unsupported"; readonly reason: string };
+
+/** Exactly one top-level `models:` and at most one `embed:` inside it. */
+function isWellFormed(content: string): boolean {
+ const models = content.match(/^models:/gm) ?? [];
+ if (models.length !== 1) return false;
+ const block = MODELS_BLOCK_RE.exec(content);
+ return (block?.[0].match(/^[ \t]+embed:/gm) ?? []).length <= 1;
+}
+
+/**
+ * Set `models.embed` to `desired` in a qmd config, preserving everything else.
+ *
+ * Pure, so the policy — replace the default, keep a deliberate choice, do
+ * nothing when already correct, refuse what it cannot edit — is testable
+ * without a filesystem or a qmd.
+ *
+ * CRLF is normalised for matching and restored on the way out: a config written
+ * on Windows otherwise misses every anchored pattern here, and the miss lands
+ * in the append branch rather than failing visibly.
+ */
+export function upsertEmbedModelInYaml(
+ content: string,
+ desired: string,
+): EmbedModelPatch {
+ const crlf = content.includes("\r\n");
+ const text = crlf ? content.replace(/\r\n/g, "\n") : content;
+ const restore = (out: string): string => (crlf ? out.replace(/\n/g, "\r\n") : out);
+
+ const block = MODELS_BLOCK_RE.exec(text);
+
+ if (!block) {
+ // A `models:` key that did not parse as an editable block. Appending here
+ // would duplicate the key and make the file unloadable, so stop instead.
+ if (MODELS_KEY_RE.test(text)) {
+ return {
+ kind: "unsupported",
+ reason: "a `models:` key that is not a block mapping this can edit",
+ };
+ }
+ const separator = text.endsWith("\n") || text.length === 0 ? "" : "\n";
+ const out = `${text}${separator}models:\n embed: ${desired}\n`;
+ return isWellFormed(out)
+ ? { kind: "updated", content: restore(out) }
+ : { kind: "unsupported", reason: "appending a models block would not be well-formed" };
+ }
+
+ const embed = EMBED_LINE_RE.exec(block[0]);
+ const splice = (patchedBlock: string): EmbedModelPatch => {
+ const out =
+ text.slice(0, block.index) +
+ patchedBlock +
+ text.slice(block.index + block[0].length);
+ // The guard, not a formality: every corruption this function could cause
+ // shows up as a duplicate key, so refuse to hand one back.
+ return isWellFormed(out)
+ ? { kind: "updated", content: restore(out) }
+ : { kind: "unsupported", reason: "the edit would have produced a duplicate key" };
+ };
+
+ if (!embed) {
+ return splice(block[0].replace(/^models:/, `models:\n embed: ${desired}`).replace(/^(models:\n embed: [^\n]*)\n[ \t]*(?:#[^\n]*)?\n/, "$1\n"));
+ }
+
+ // An `embed:` key with no value is unset, not chosen — the improvement
+ // applies, and the line is replaced rather than a second one inserted.
+ const current = yamlScalar(embed[2] ?? "");
+ if (current === desired) return { kind: "already-set" };
+ if (current !== "" && !QMD_SHIPPED_DEFAULTS.has(current)) {
+ return { kind: "user-chosen", current };
+ }
+ return splice(block[0].replace(EMBED_LINE_RE, `$1embed: ${desired}`));
+}
+
+/**
+ * Apply {@link upsertEmbedModelInYaml} to a config on disk.
+ *
+ * Returns true when the file changed, which is exactly the condition under
+ * which the caller has to force a re-embed. A missing config is not an error:
+ * qmd has simply not created it yet, and the next bootstrap run will.
+ */
+export function writeQmdEmbedModel(
+ configPath: string,
+ desired: string = PREFERRED_EMBED_MODEL,
+): boolean {
+ let before: string;
+ try {
+ before = readFileSync(configPath, "utf-8");
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
+ warn(`QMD config not found at ${configPath}; embedding model not set.`);
+ return false;
+ }
+ throw err;
+ }
+ const result = upsertEmbedModelInYaml(before, desired);
+ if (result.kind === "already-set") return false;
+ if (result.kind === "user-chosen") {
+ warn(
+ `QMD embedding model is set to ${result.current}, which is neither qmd's default nor this template's; leaving it alone.`,
+ );
+ return false;
+ }
+ if (result.kind === "unsupported") {
+ warn(
+ `QMD config at ${configPath} has ${result.reason}; embedding model not set. Set models.embed to ${desired} by hand, then run \`qmd embed -f\`.`,
+ );
+ return false;
+ }
+ writeFileSync(configPath, result.content, "utf-8");
+ return true;
+}
diff --git a/.claude/scripts/tests/mcp-qmd-client.test.ts b/.claude/scripts/tests/mcp-qmd-client.test.ts
index e387052..0fc2050 100644
--- a/.claude/scripts/tests/mcp-qmd-client.test.ts
+++ b/.claude/scripts/tests/mcp-qmd-client.test.ts
@@ -157,23 +157,27 @@ describe("building sub-queries", () => {
assert.ok(types.includes("vec"));
});
- test("a question-shaped query also gets hyde", () => {
- // hyde writes a hypothetical answer and matches against that, which is
- // what finds the note whose title shares no words with the question.
+ test("hyde is never sent, whatever the query looks like", () => {
+ // qmd treats `hyde` as a label on a vector search, not a mode: generation
+ // runs in expandQuery(), which only the plain-text `query` parameter
+ // reaches. A `hyde` sub-query holding the raw question IS the `vec` entry
+ // above, issued a second time and paid for twice.
for (const q of [
"why did we choose postgres over mysql",
"how does the retry envelope behave",
"what happens when the lease expires?",
+ "caching",
]) {
- assert.ok(subQueries(q).some((s) => s.type === "hyde"), q);
+ assert.ok(!subQueries(q).some((s) => s.type === "hyde"), q);
}
});
- test("a keyword lookup does NOT pay for hyde", () => {
- // It runs a local generation model. Lexical matching is already the right
- // tool for a two-word lookup, so the cost buys nothing.
- for (const q of ["caching", "deploy runbook", "retry envelope", "postgres"]) {
- assert.ok(!subQueries(q).some((s) => s.type === "hyde"), q);
+ test("a question-shaped query gets exactly lex and vec, like every other", () => {
+ // Guards the removal. A question used to grow a third sub-query for
+ // +35-40ms and no measured gain; re-adding one should fail here rather
+ // than quietly costing that again.
+ for (const q of ["why did we choose postgres over mysql", "what happens when the lease expires?"]) {
+ assert.deepEqual(subQueries(q).map((s) => s.type), ["lex", "vec"], q);
}
});
diff --git a/.claude/scripts/tests/qmd-models.test.ts b/.claude/scripts/tests/qmd-models.test.ts
new file mode 100644
index 0000000..466fce3
--- /dev/null
+++ b/.claude/scripts/tests/qmd-models.test.ts
@@ -0,0 +1,205 @@
+/**
+ * Unit tests for lib/qmd-models — choosing the embedding model.
+ *
+ * The policy is the whole point and it is three-way: replace qmd's default,
+ * keep a deliberate choice, do nothing when it is already right. Getting the
+ * middle case wrong would silently overwrite a user's setting on every
+ * bootstrap, and getting the last one wrong would force a full re-embed every
+ * run, so both are locked here.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ PREFERRED_EMBED_MODEL,
+ QMD_DEFAULT_EMBED_MODEL,
+ upsertEmbedModelInYaml,
+ writeQmdEmbedModel,
+} from "../lib/qmd-models.ts";
+
+import { rmTemp } from "./_helpers.ts";
+
+const CONFIG = (embed: string) =>
+ `collections:\n vault:\n path: /somewhere\n pattern: "**/*.md"\nmodels:\n embed: ${embed}\n generate: hf:some/generate.gguf\n rerank: hf:some/rerank.gguf\n`;
+
+describe("choosing the embedding model", () => {
+ test("qmd's default is replaced", () => {
+ const r = upsertEmbedModelInYaml(CONFIG(QMD_DEFAULT_EMBED_MODEL), PREFERRED_EMBED_MODEL);
+ assert.equal(r.kind, "updated");
+ assert.ok(r.kind === "updated" && r.content.includes(`embed: ${PREFERRED_EMBED_MODEL}`));
+ });
+
+ test("a model somebody chose is never overwritten", () => {
+ // A template supplies a better default. It does not overrule a choice —
+ // and on every bootstrap run, which is what makes this the dangerous one.
+ const mine = "hf:someone/their-own-embedder.gguf";
+ const r = upsertEmbedModelInYaml(CONFIG(mine), PREFERRED_EMBED_MODEL);
+ assert.equal(r.kind, "user-chosen");
+ assert.equal(r.kind === "user-chosen" && r.current, mine);
+ });
+
+ test("already correct is not a change", () => {
+ // A write here would be harmless but the caller reads this as "the model
+ // changed" and forces a full re-embed, so it must not report one.
+ assert.equal(
+ upsertEmbedModelInYaml(CONFIG(PREFERRED_EMBED_MODEL), PREFERRED_EMBED_MODEL).kind,
+ "already-set",
+ );
+ });
+
+ test("everything else in the file survives the edit", () => {
+ // The config also carries the collection, its glob, ignore patterns and
+ // the context string. Losing any of them would be a far worse bug than
+ // the one being fixed.
+ const before =
+ `collections:\n vault:\n path: /somewhere\n pattern: "**/*.md"\n ignore:\n - "drafts/**"\n context:\n "": A description of the vault.\nmodels:\n embed: ${QMD_DEFAULT_EMBED_MODEL}\n generate: hf:some/generate.gguf\n`;
+ const r = upsertEmbedModelInYaml(before, PREFERRED_EMBED_MODEL);
+ assert.equal(r.kind, "updated");
+ if (r.kind !== "updated") return;
+ for (const kept of [
+ "path: /somewhere",
+ 'pattern: "**/*.md"',
+ '- "drafts/**"',
+ '"": A description of the vault.',
+ "generate: hf:some/generate.gguf",
+ ]) {
+ assert.ok(r.content.includes(kept), kept);
+ }
+ });
+
+ test("a shape it cannot edit is refused, never appended to", () => {
+ // The corruption this guards is the expensive one: appending a second
+ // top-level `models:` makes the file unparseable, and qmd rethrows that
+ // as a config error that takes every collection and all search with it.
+ const r = upsertEmbedModelInYaml(
+ `collections:\n v:\n path: /x\nmodels: {embed: ${QMD_DEFAULT_EMBED_MODEL}}\n`,
+ PREFERRED_EMBED_MODEL,
+ );
+ assert.equal(r.kind, "unsupported");
+ });
+
+ test("no edit ever produces a duplicate key", () => {
+ // One assertion over every spelling that reached the append branch before:
+ // CRLF from a Windows host, a trailing space, a commented header, and an
+ // `embed:` key with no value. Each one used to yield two `models:` keys
+ // or two `embed:` keys.
+ const D = QMD_DEFAULT_EMBED_MODEL;
+ for (const [label, input] of [
+ ["CRLF", `collections:\r\n v:\r\n path: /x\r\nmodels:\r\n embed: ${D}\r\n`],
+ ["trailing space", `collections:\n v:\n path: /x\nmodels: \n embed: ${D}\n`],
+ ["commented header", `collections:\n v:\n path: /x\nmodels: # embedders\n embed: ${D}\n`],
+ ["empty value", `collections:\n v:\n path: /x\nmodels:\n embed:\n rerank: hf:r\n`],
+ ] as const) {
+ const r = upsertEmbedModelInYaml(input, PREFERRED_EMBED_MODEL);
+ assert.equal(r.kind, "updated", label);
+ if (r.kind !== "updated") continue;
+ assert.equal((r.content.match(/^models:/gm) ?? []).length, 1, label);
+ assert.equal((r.content.match(/^[ \t]+embed:/gm) ?? []).length, 1, label);
+ assert.ok(r.content.includes(`embed: ${PREFERRED_EMBED_MODEL}`), label);
+ }
+ });
+
+ test("a CRLF file stays CRLF", () => {
+ // Rewriting a Windows config as LF would show up as every line changed in
+ // whatever the user diffs it with.
+ const r = upsertEmbedModelInYaml(
+ `collections:\r\n v:\r\n path: /x\r\nmodels:\r\n embed: ${QMD_DEFAULT_EMBED_MODEL}\r\n`,
+ PREFERRED_EMBED_MODEL,
+ );
+ assert.equal(r.kind, "updated");
+ assert.ok(r.kind === "updated" && r.content.includes("\r\n"));
+ assert.ok(r.kind === "updated" && !/[^\r]\n/.test(r.content));
+ });
+
+ test("qmd's default is recognised through quotes and comments", () => {
+ // Otherwise the decoration reads as a deliberate choice, the vault keeps
+ // the worse embedder, and the warning tells the user their model is
+ // neither qmd's default nor ours — when it is exactly qmd's default.
+ for (const spelling of [
+ `"${QMD_DEFAULT_EMBED_MODEL}"`,
+ `'${QMD_DEFAULT_EMBED_MODEL}'`,
+ `${QMD_DEFAULT_EMBED_MODEL} # qmd's default`,
+ ]) {
+ const r = upsertEmbedModelInYaml(
+ `collections:\n v:\n path: /x\nmodels:\n embed: ${spelling}\n`,
+ PREFERRED_EMBED_MODEL,
+ );
+ assert.equal(r.kind, "updated", spelling);
+ }
+ });
+
+ test("an embed key with no value is unset, not chosen", () => {
+ const r = upsertEmbedModelInYaml(
+ `collections:\n v:\n path: /x\nmodels:\n embed:\n rerank: hf:r\n`,
+ PREFERRED_EMBED_MODEL,
+ );
+ assert.equal(r.kind, "updated");
+ assert.ok(r.kind === "updated" && r.content.includes("rerank: hf:r"));
+ });
+
+ test("a config with no models block gets one", () => {
+ const r = upsertEmbedModelInYaml(`collections:\n vault:\n path: /somewhere\n`, PREFERRED_EMBED_MODEL);
+ assert.equal(r.kind, "updated");
+ assert.ok(r.kind === "updated" && r.content.includes(`models:\n embed: ${PREFERRED_EMBED_MODEL}`));
+ });
+
+ test("a models block without an embed key gets one, keeping its siblings", () => {
+ const r = upsertEmbedModelInYaml(`collections:\n vault:\n path: /x\nmodels:\n rerank: hf:some/rerank.gguf\n`, PREFERRED_EMBED_MODEL);
+ assert.equal(r.kind, "updated");
+ assert.ok(r.kind === "updated" && r.content.includes(`embed: ${PREFERRED_EMBED_MODEL}`));
+ assert.ok(r.kind === "updated" && r.content.includes("rerank: hf:some/rerank.gguf"));
+ });
+
+ test("the result is valid input to itself", () => {
+ // Bootstrap is documented as safe to re-run, so a second pass over its
+ // own output must report no change rather than churn the file.
+ const first = upsertEmbedModelInYaml(CONFIG(QMD_DEFAULT_EMBED_MODEL), PREFERRED_EMBED_MODEL);
+ assert.equal(first.kind, "updated");
+ if (first.kind !== "updated") return;
+ assert.equal(upsertEmbedModelInYaml(first.content, PREFERRED_EMBED_MODEL).kind, "already-set");
+ });
+});
+
+describe("writing the embedding model to disk", () => {
+ test("a changed file reports true, an unchanged one false", () => {
+ const dir = mkdtempSync(join(tmpdir(), "qmd-models-"));
+ try {
+ const p = join(dir, "vault.yml");
+ writeFileSync(p, CONFIG(QMD_DEFAULT_EMBED_MODEL), "utf-8");
+ // True is what makes the caller force a re-embed; the two must agree.
+ assert.equal(writeQmdEmbedModel(p), true);
+ assert.ok(readFileSync(p, "utf-8").includes(`embed: ${PREFERRED_EMBED_MODEL}`));
+ assert.equal(writeQmdEmbedModel(p), false);
+ } finally {
+ rmTemp(dir);
+ }
+ });
+
+ test("an unsupported config is left untouched on disk", () => {
+ const dir = mkdtempSync(join(tmpdir(), "qmd-models-"));
+ try {
+ const p = join(dir, "vault.yml");
+ const before = `collections:\n v:\n path: /x\nmodels: {embed: ${QMD_DEFAULT_EMBED_MODEL}}\n`;
+ writeFileSync(p, before, "utf-8");
+ assert.equal(writeQmdEmbedModel(p), false);
+ assert.equal(readFileSync(p, "utf-8"), before);
+ } finally {
+ rmTemp(dir);
+ }
+ });
+
+ test("a missing config is not an error", () => {
+ // qmd creates it on first use. A fresh clone reaching here early should
+ // warn and carry on, not abort the bootstrap.
+ const dir = mkdtempSync(join(tmpdir(), "qmd-models-"));
+ try {
+ assert.equal(writeQmdEmbedModel(join(dir, "nope.yml")), false);
+ } finally {
+ rmTemp(dir);
+ }
+ });
+});
diff --git a/.scripts/qmd-bootstrap.ts b/.scripts/qmd-bootstrap.ts
index 355d290..60de92d 100644
--- a/.scripts/qmd-bootstrap.ts
+++ b/.scripts/qmd-bootstrap.ts
@@ -51,6 +51,7 @@ import {
translateToGlob,
writeQmdIgnore,
} from "../.claude/scripts/lib/qmd-ignore.ts";
+import { writeQmdEmbedModel } from "../.claude/scripts/lib/qmd-models.ts";
import {
deriveQmdIndex,
isValidQmdIndex,
@@ -421,8 +422,27 @@ function main(): void {
}
}
+ // Set the embedding model before indexing. qmd materialises its own default
+ // into the config the first time it touches an index, so this has to run
+ // after the collection exists and before anything is embedded.
+ //
+ // Changing it invalidates every existing vector — the two models produce
+ // different dimensions, and qmd refuses to mix them: `embed` errors out and
+ // a query throws outright rather than degrading. So a change here forces a
+ // full re-embed in the same run, and the two are never left apart.
+ const embedderChanged = writeQmdEmbedModel(qmdConfigPath(index));
+ if (embedderChanged) {
+ process.stdout.write("→ Setting the embedding model\n");
+ }
+
run(entry, ["--index", index, "update"], "Indexing vault files");
- run(entry, ["--index", index, "embed"], "Generating embeddings");
+ run(
+ entry,
+ ["--index", index, "embed", ...(embedderChanged ? ["-f"] : [])],
+ embedderChanged
+ ? "Generating embeddings (full rebuild — the model changed)"
+ : "Generating embeddings",
+ );
process.stdout.write(
`\n✓ QMD index '${index}' ready. Test with:\n qmd --index ${index} query "<topic>"\n`,
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 3677f36..0b6d097 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -225,10 +225,14 @@ Worth understanding, because it explains the cost profile of everything built on
| model | size | job |
|---|---|---|
-| `embeddinggemma-300M` | ~328 MB | turns notes and queries into vectors |
-| `qmd-query-expansion-1.7B` | ~1.28 GB | rewrites a query into better search terms, and writes hypothetical answers for HyDE |
+| `Qwen3-Embedding-0.6B` | ~640 MB | turns notes and queries into vectors |
+| `qmd-query-expansion-1.7B` | ~1.28 GB | rewrites a query into better search terms, and writes hypothetical answers for HyDE — reached by the `qmd query` CLI, not by the typed sub-queries this template sends (see below) |
| `Qwen3-Reranker-0.6B` | ~640 MB | reorders the shortlist by actual relevance |
+**The embedder is chosen, not inherited.** qmd defaults to `embeddinggemma-300M`, and the bootstrap replaces it. Measured on a 684-document vault against 211 human-labelled retrieval pairs, query path otherwise untouched: rank-1 0.299 → 0.469 and found@5 0.521 → 0.758 (McNemar exact p < 0.0001), replicated on a second independently written vault at rank-1 0.650 → 0.950 (p = 0.0003). It costs ~13ms a query and roughly doubles a full index build. Reranking is not a cheaper substitute for it — on the default embedder reranking is a large significant gain, on this one it is not significant on rank-1, because it had been compensating for the embedder; this model with no reranker beats the default with one, at an eighth of the latency.
+
+Set `models.embed` in the qmd config yourself and the bootstrap leaves it alone — it replaces qmd's default, never a choice. Changing the model invalidates every existing vector, since the two produce different dimensions and qmd refuses to mix them, so the bootstrap forces a full re-embed in the same run.
+
They download on first use and are cached. QMD offloads to the GPU when it finds one — CUDA on a discrete card, Metal on Apple Silicon — and falls back to CPU otherwise. `qmd doctor` reports which.
The CLI verbs map onto that stack, cheapest first:
@@ -578,7 +582,7 @@ sequenceDiagram
OM->>Exp: allowedSearchPaths(vault, policy)
Exp-->>OM: set of vault-relative keys
OM->>QC: qmdSearch(allowed, query, limit)
- QC->>QC: subQueries → lex + vec (+ hyde if question-shaped)
+ QC->>QC: subQueries → lex + vec
QC->>QMD: tools/call query, limit = max(limit*4, 20)
QMD-->>QC: structuredContent.results — the WHOLE vault
QC->>QC: filter each hit against allowed
@@ -595,7 +599,7 @@ Four details in that flow are decisions rather than mechanics:
**Over-fetch, then trim.** Because the filter runs on the result, asking qmd for exactly `limit` means a vault with much unserved content returns far fewer than requested with no sign that more existed. The client asks for `max(limit * 4, 20)`.
-**HyDE is conditional.** `lex` and `vec` always go out together — keywords find the exact term, vectors find the note that answers the question without using the word. `hyde` writes a hypothetical answer and matches against *that*, which is what finds the note whose title shares no words with the question. It runs a local generation model, so it is added only for queries that are at least four words *and* question-shaped. A two-word keyword lookup, where lexical matching is already the right tool, does not pay for it.
+**`lex` and `vec`, and deliberately nothing else.** Keywords find the exact term, vectors find the note that answers the question without using the word. There is no `hyde` sub-query, because qmd treats `hyde` as a *label* on a vector search rather than as a mode — as of 2.8.3 every site in its store reads `type === 'vec' || type === 'hyde'`, and generation happens only inside `expandQuery()`, which the plain-text `query` parameter reaches and a `searches` array bypasses. Passing the raw question in a `hyde` slot therefore repeats the `vec` search already going out, and pays for both: measured over 211 human-labelled pairs, sending it never, conditionally or always gave identical rank-1 and found@5 to four decimal places for +35-40ms a query. An *authored* hyde — a caller-written passage describing what the answer would look like — is a real technique and the `SubQuery` type still allows it; handing it the user's question is not that.
**Degradation is explicit.** qmd is optional in this template. A failed call degrades that one search and says so; it must never present as "the vault is empty". The client tracks liveness, so one qmd crash does not disable search for the life of the server, and the entry script replaces a dead child behind a 5-second cooldown so a permanently-broken qmd cannot fork a process per call.