Skip to content

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

fix: derive the qmd index per vault instead of shipping a shared name (#154)

Brenno Ferrari90574df6ea58
diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.ts
index 0d990ac..029f68e 100644
--- a/.claude/scripts/lib/session-start.ts
+++ b/.claude/scripts/lib/session-start.ts
@@ -4,7 +4,7 @@
* system, or invoking the Obsidian CLI.
*/
-import { join } from "node:path";
+import { basename, join, resolve } from "node:path";
import { escapeRegex } from "./regex.ts";
@@ -410,6 +410,88 @@ export function parseQmdIndex(manifestJson: string | null): string | null {
return null;
}
+/**
+ * Derive a qmd index name from the vault's own directory name.
+ *
+ * The shipped manifest leaves `qmd_index` empty because the template is one
+ * package installed many times — any literal it ships is identical in every
+ * vault, so two vaults on one machine share a single SQLite store, search
+ * bleeds across them, and re-indexing one clobbers the other (#137). The
+ * install location is the only per-vault identity available without asking
+ * the user a question, and it exists on both install paths.
+ *
+ * The slug rules mirror ShardMind's `slugifyVaultName` (shardmind#143)
+ * deliberately: if a future engine-side substitution ever bakes the name in,
+ * it resolves to the same string this derives, so the two mechanisms cannot
+ * disagree about which store a vault owns.
+ *
+ * Returns null when the folder name has no usable characters (e.g. a purely
+ * non-Latin name), so the caller falls back rather than emitting a broken
+ * index name.
+ */
+export function deriveQmdIndex(vaultRoot: string): string | null {
+ const slug = basename(resolve(vaultRoot))
+ .normalize("NFKD")
+ .toLowerCase()
+ .replace(/[^a-z0-9._-]+/g, "-")
+ .replace(/-{2,}/g, "-")
+ .replace(/^[^a-z0-9]+|[-._]+$/g, "");
+ return isValidQmdIndex(slug) ? slug : null;
+}
+
+/**
+ * Extract a validated `template` name from a manifest source — the shared
+ * package identity, and the last-resort index name when a vault has neither
+ * a pin nor a derivable folder slug.
+ */
+function parseTemplateName(manifestJson: string | null): string | null {
+ if (manifestJson === null) return null;
+ try {
+ const parsed = JSON.parse(manifestJson) as unknown;
+ if (parsed !== null && typeof parsed === "object") {
+ const value = (parsed as Record<string, unknown>)["template"];
+ if (isValidQmdIndex(value)) return value;
+ }
+ } catch {
+ /* malformed manifest → treat as missing */
+ }
+ return null;
+}
+
+/**
+ * The index name this vault owns, in precedence order:
+ *
+ * 1. an explicit `qmd_index` pin,
+ * 2. the vault folder name, slugified,
+ * 3. the manifest `template` name — shared across installs, so it
+ * reintroduces the collision #137 fixes, but a working shared store
+ * beats silently indexing somewhere nobody reads.
+ *
+ * Every caller MUST route through here. There are four (SessionStart, the
+ * mid-session refresh worker, the MCP wrapper, the bootstrap script) and they
+ * do not fail loudly when they disagree — one writes to a store another never
+ * reads, which surfaces as "0 documents". Step 3 exists because an earlier
+ * revision had bootstrap fall back to `template` while the read surfaces fell
+ * back to qmd's global index, producing exactly that split.
+ *
+ * Keeping the pin as an override is what makes derivation safe to adopt: a
+ * vault that wants a name surviving a folder rename — or wants to keep a store
+ * it already built — pins the field and nothing derives.
+ *
+ * Null means "use qmd's default global index" and is reachable only when the
+ * manifest is absent or carries neither field.
+ */
+export function resolveQmdIndex(
+ manifestJson: string | null,
+ vaultRoot: string,
+): string | null {
+ return (
+ parseQmdIndex(manifestJson) ??
+ deriveQmdIndex(vaultRoot) ??
+ parseTemplateName(manifestJson)
+ );
+}
+
/**
* Build the argv tail for a `qmd` CLI invocation, prepending `--index <name>`
* when the vault has configured a named index. Callers pass the subcommand
diff --git a/.claude/scripts/qmd-mcp.d.mts b/.claude/scripts/qmd-mcp.d.mts
index d011953..cff9d73 100644
--- a/.claude/scripts/qmd-mcp.d.mts
+++ b/.claude/scripts/qmd-mcp.d.mts
@@ -26,6 +26,22 @@ export function resolveVaultRoot(
*/
export function readQmdIndex(manifestJson: string | null): string | null;
+/**
+ * Derive an index name from the vault folder, slugified. Returns null when
+ * the folder name yields nothing usable. Mirrors
+ * `lib/session-start.ts:deriveQmdIndex`; the tests assert the two agree.
+ */
+export function deriveQmdIndex(vaultRoot: string): string | null;
+
+/**
+ * The index this vault owns: an explicit `qmd_index` pin wins, else the
+ * folder-derived slug. Null means "use QMD's default global index".
+ */
+export function resolveQmdIndex(
+ manifestJson: string | null,
+ vaultRoot: string,
+): string | null;
+
/**
* Compute the SQLite store path qmd would use for a given named index,
* using the same rule as @tobilu/qmd's store.js.
diff --git a/.claude/scripts/qmd-mcp.mjs b/.claude/scripts/qmd-mcp.mjs
index 5b49de3..25af538 100644
--- a/.claude/scripts/qmd-mcp.mjs
+++ b/.claude/scripts/qmd-mcp.mjs
@@ -28,7 +28,7 @@
import { spawn, spawnSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
-import { dirname, isAbsolute, join, resolve } from "node:path";
+import { basename, dirname, isAbsolute, join, resolve } from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath, pathToFileURL } from "node:url";
import { homedir } from "node:os";
@@ -134,6 +134,65 @@ export function readQmdIndex(manifestJson) {
return null;
}
+/**
+ * Derive an index name from the vault folder. Duplicated from
+ * `lib/session-start.ts:deriveQmdIndex` for the same reason as the pattern
+ * above (this file is .mjs and can't import the .ts lib at strip-types
+ * runtime); the tests assert both copies agree.
+ *
+ * Returns null when the folder name yields no usable slug.
+ */
+export function deriveQmdIndex(vaultRoot) {
+ const slug = basename(resolve(vaultRoot))
+ .normalize("NFKD")
+ .toLowerCase()
+ .replace(/[^a-z0-9._-]+/g, "-")
+ .replace(/-{2,}/g, "-")
+ .replace(/^[^a-z0-9]+|[-._]+$/g, "");
+ return QMD_INDEX_PATTERN.test(slug) ? slug : null;
+}
+
+/**
+ * Read a validated `template` name — the last-resort index name when there is
+ * neither a pin nor a derivable folder slug.
+ */
+function readTemplateName(manifestJson) {
+ if (manifestJson === null) return null;
+ try {
+ const parsed = JSON.parse(manifestJson);
+ if (
+ parsed !== null &&
+ typeof parsed === "object" &&
+ typeof parsed.template === "string" &&
+ QMD_INDEX_PATTERN.test(parsed.template)
+ ) {
+ return parsed.template;
+ }
+ } catch {
+ /* malformed manifest → treat as missing */
+ }
+ return null;
+}
+
+/**
+ * The index this vault owns: explicit `qmd_index` pin, else the folder-derived
+ * slug, else the shared `template` name (#137). Null means "use QMD's default
+ * global index".
+ *
+ * The MCP wrapper MUST resolve this exactly the way the SessionStart hook, the
+ * refresh worker, and the bootstrap script do — a disagreement points the
+ * agent's search at a different store than the one being indexed, and fails as
+ * "0 documents" rather than as an error. Mirrors
+ * `lib/session-start.ts:resolveQmdIndex`; the tests assert the two agree.
+ */
+export function resolveQmdIndex(manifestJson, vaultRoot) {
+ return (
+ readQmdIndex(manifestJson) ??
+ deriveQmdIndex(vaultRoot) ??
+ readTemplateName(manifestJson)
+ );
+}
+
/**
* Compute the SQLite store path qmd would use for a given named index, using
* the same rule as @tobilu/qmd's store.js (XDG_CACHE_HOME || ~/.cache +
@@ -175,7 +234,7 @@ function readManifestRaw() {
}
function runAsMcp() {
- const qmdIndex = readQmdIndex(readManifestRaw());
+ const qmdIndex = resolveQmdIndex(readManifestRaw(), VAULT_ROOT);
if (qmdIndex && !process.env["INDEX_PATH"]) {
// Apply the qmd 2.1.0 MCP bug workaround: pin the SQLite store to the
diff --git a/.claude/scripts/qmd-refresh-run.ts b/.claude/scripts/qmd-refresh-run.ts
index 91f72b0..98d4213 100644
--- a/.claude/scripts/qmd-refresh-run.ts
+++ b/.claude/scripts/qmd-refresh-run.ts
@@ -35,7 +35,7 @@ import { readFileSync } from "node:fs";
import { dirname, resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
import { debug } from "./lib/hook-io.ts";
-import { parseQmdIndex } from "./lib/session-start.ts";
+import { resolveQmdIndex } from "./lib/session-start.ts";
import { resolveQmdEntry } from "./lib/qmd.ts";
import {
composeWorkerInvocations,
@@ -54,7 +54,11 @@ function readManifestRaw(): string | null {
}
}
-const qmdIndex = parseQmdIndex(readManifestRaw());
+// Must resolve the index exactly as SessionStart, the MCP wrapper, and the
+// bootstrap script do. This worker WRITES to the store; if it resolved
+// differently it would index one store while search reads another, and the
+// symptom is stale results rather than an error.
+const qmdIndex = resolveQmdIndex(readManifestRaw(), VAULT_ROOT);
const invocations = composeWorkerInvocations(qmdIndex, resolveQmdEntry());
for (const inv of invocations) {
diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.ts
index 22f450b..aa3cc20 100644
--- a/.claude/scripts/session-start.ts
+++ b/.claude/scripts/session-start.ts
@@ -33,7 +33,7 @@ import {
formatBrainIndex,
stripFrontmatter,
hasBrainContent,
- parseQmdIndex,
+ resolveQmdIndex,
parseQmdMinVersion,
qmdArgsWithIndex,
isQmdNativeAbiMismatch,
@@ -134,11 +134,13 @@ const infraRootFilenames = parseInfraRootFilenames(manifestJson);
// emission) is independent of this index update, so blocking on qmd's
// startup (notably slow on Windows × Node 24 cold start, where it can
// approach 10s before the actual update work begins) is wasted user
-// latency. Scope to this vault's named index when the manifest declares
-// one; fall back silently for forks that haven't adopted `qmd_index`.
+// latency. Scope to this vault's named index: an explicit `qmd_index` when
+// the manifest pins one, otherwise a slug derived from the vault folder so
+// two vaults on one machine don't share a store (#137). Falls back silently
+// to qmd's global index for forks that have neither.
// Route through `buildQmdCommand` so the shim-bypass logic that fixes
// the MCP wrapper applies here too.
-const qmdIndex = parseQmdIndex(manifestJson);
+const qmdIndex = resolveQmdIndex(manifestJson, cwd);
const qmdEntry = resolveQmdEntry();
// qmd is OPTIONAL in this template: every self-heal path below is gated on
diff --git a/.claude/scripts/tests/qmd-mcp.test.ts b/.claude/scripts/tests/qmd-mcp.test.ts
index 95c70f0..d46c669 100644
--- a/.claude/scripts/tests/qmd-mcp.test.ts
+++ b/.claude/scripts/tests/qmd-mcp.test.ts
@@ -26,7 +26,13 @@ import {
readQmdIndex,
resolveIndexSqlitePath,
resolveVaultRoot,
+ deriveQmdIndex as deriveQmdIndexMjs,
+ resolveQmdIndex as resolveQmdIndexMjs,
} from "../qmd-mcp.mjs";
+import {
+ deriveQmdIndex as deriveQmdIndexTs,
+ resolveQmdIndex as resolveQmdIndexTs,
+} from "../lib/session-start.ts";
describe("resolveQmdEntry", () => {
test("returns an absolute path to an existing qmd entrypoint when qmd is installed", () => {
@@ -248,3 +254,164 @@ describe("resolveIndexSqlitePath", () => {
assert.doesNotMatch(out, /AppData/);
});
});
+
+/**
+ * The MCP wrapper is `.mjs` and cannot import the `.ts` lib at strip-types
+ * runtime, so `deriveQmdIndex` exists twice. A drift between the two copies
+ * is the worst kind of bug this template can have: the SessionStart hook
+ * would index one store while the agent's search reads another, and the
+ * symptom is "0 documents" rather than an error. These tests are the only
+ * thing holding the copies together.
+ */
+describe("qmd index derivation — .mjs and .ts copies agree", () => {
+ const CASES = [
+ "vigil-mind",
+ "Obsidian Mind",
+ "MY_VAULT",
+ "vault.with.dots",
+ "trailing---dashes---",
+ "-leading-dash",
+ "UPPER",
+ "a",
+ "work vault (2026)",
+ "...",
+ "日本語",
+ ];
+
+ for (const name of CASES) {
+ test(`agree on ${JSON.stringify(name)}`, () => {
+ const root = `/tmp/${name}`;
+ assert.equal(deriveQmdIndexMjs(root), deriveQmdIndexTs(root));
+ });
+ }
+
+ test("agree when a manifest pins the index", () => {
+ const manifest = JSON.stringify({ qmd_index: "pinned-name" });
+ assert.equal(
+ resolveQmdIndexMjs(manifest, "/tmp/ignored"),
+ resolveQmdIndexTs(manifest, "/tmp/ignored"),
+ );
+ });
+
+ test("agree when the manifest is absent", () => {
+ assert.equal(
+ resolveQmdIndexMjs(null, "/tmp/some-vault"),
+ resolveQmdIndexTs(null, "/tmp/some-vault"),
+ );
+ });
+});
+
+describe("deriveQmdIndex", () => {
+ test("uses the vault folder name, slugified", () => {
+ assert.equal(deriveQmdIndexTs("/home/me/Obsidian Mind"), "obsidian-mind");
+ });
+
+ test("lowercases and collapses runs of separators", () => {
+ assert.equal(deriveQmdIndexTs("/x/My Work__Vault"), "my-work__vault");
+ });
+
+ test("strips leading non-alphanumerics and trailing separators", () => {
+ assert.equal(deriveQmdIndexTs("/x/--vault--"), "vault");
+ });
+
+ test("keeps dots, dashes and underscores", () => {
+ assert.equal(deriveQmdIndexTs("/x/a.b-c_d"), "a.b-c_d");
+ });
+
+ test("returns null when nothing usable remains", () => {
+ assert.equal(deriveQmdIndexTs("/x/日本語"), null);
+ assert.equal(deriveQmdIndexTs("/x/..."), null);
+ });
+
+ test("never yields a value that fails the index validator", () => {
+ for (const name of ["ok", "A B", "...", "-x-", "1", "_a"]) {
+ const out = deriveQmdIndexTs(`/x/${name}`);
+ if (out !== null) assert.match(out, /^[A-Za-z0-9][A-Za-z0-9._-]*$/);
+ }
+ });
+});
+
+describe("resolveQmdIndex", () => {
+ test("an explicit pin beats the folder name", () => {
+ assert.equal(
+ resolveQmdIndexTs(JSON.stringify({ qmd_index: "pinned" }), "/x/folder"),
+ "pinned",
+ );
+ });
+
+ test("an empty qmd_index falls through to derivation", () => {
+ assert.equal(
+ resolveQmdIndexTs(JSON.stringify({ qmd_index: "" }), "/x/my-vault"),
+ "my-vault",
+ );
+ });
+
+ test("a missing qmd_index falls through to derivation", () => {
+ assert.equal(resolveQmdIndexTs(JSON.stringify({}), "/x/my-vault"), "my-vault");
+ });
+
+ test("an invalid pin falls through rather than propagating a bad name", () => {
+ assert.equal(
+ resolveQmdIndexTs(JSON.stringify({ qmd_index: "has/slash" }), "/x/my-vault"),
+ "my-vault",
+ );
+ });
+
+ test("returns null when there is no pin and nothing to derive", () => {
+ assert.equal(resolveQmdIndexTs(JSON.stringify({}), "/x/日本語"), null);
+ });
+
+ test("two vaults in different folders resolve to different indexes", () => {
+ const manifest = JSON.stringify({ qmd_index: "" });
+ assert.notEqual(
+ resolveQmdIndexTs(manifest, "/a/vault-one"),
+ resolveQmdIndexTs(manifest, "/b/vault-two"),
+ );
+ });
+});
+
+/**
+ * The `template` fallback tier (Copilot review on #154). An earlier revision
+ * had the bootstrap script fall back to `template` privately while the read
+ * surfaces fell back to null (qmd's global index) — so a vault with a
+ * non-derivable folder name got its content indexed into one store while
+ * every reader looked in another. Silent, and shaped like an empty vault.
+ */
+describe("resolveQmdIndex — template fallback", () => {
+ const NON_DERIVABLE = "/x/日本語";
+
+ test("falls back to template when there is no pin and no derivable slug", () => {
+ const manifest = JSON.stringify({ qmd_index: "", template: "obsidian-mind" });
+ assert.equal(resolveQmdIndexTs(manifest, NON_DERIVABLE), "obsidian-mind");
+ });
+
+ test(".mjs agrees on the template fallback", () => {
+ const manifest = JSON.stringify({ qmd_index: "", template: "obsidian-mind" });
+ assert.equal(
+ resolveQmdIndexMjs(manifest, NON_DERIVABLE),
+ resolveQmdIndexTs(manifest, NON_DERIVABLE),
+ );
+ });
+
+ test("a derivable folder still beats template", () => {
+ const manifest = JSON.stringify({ qmd_index: "", template: "obsidian-mind" });
+ assert.equal(resolveQmdIndexTs(manifest, "/x/my-vault"), "my-vault");
+ });
+
+ test("a pin still beats both", () => {
+ const manifest = JSON.stringify({ qmd_index: "pinned", template: "obsidian-mind" });
+ assert.equal(resolveQmdIndexTs(manifest, NON_DERIVABLE), "pinned");
+ });
+
+ test("an invalid template is not used", () => {
+ const manifest = JSON.stringify({ qmd_index: "", template: "has/slash" });
+ assert.equal(resolveQmdIndexTs(manifest, NON_DERIVABLE), null);
+ assert.equal(resolveQmdIndexMjs(manifest, NON_DERIVABLE), null);
+ });
+
+ test("null only when nothing at any tier is usable", () => {
+ const manifest = JSON.stringify({ qmd_index: "" });
+ assert.equal(resolveQmdIndexTs(manifest, NON_DERIVABLE), null);
+ assert.equal(resolveQmdIndexMjs(manifest, NON_DERIVABLE), null);
+ });
+});
diff --git a/.claude/skills/qmd/SKILL.md b/.claude/skills/qmd/SKILL.md
index f20adbf..31303c5 100644
--- a/.claude/skills/qmd/SKILL.md
+++ b/.claude/skills/qmd/SKILL.md
@@ -9,7 +9,7 @@ Before reading vault files directly, search with QMD first. It returns relevant
## Tool Surfaces — Preference Order
-Pick the highest surface available and stop. All three read the same SQLite store (scoped by `qmd_index` in `vault-manifest.json`), so they return the same results; the choice is about interface ergonomics and context cost.
+Pick the highest surface available and stop. All three read the same SQLite store (see [Named Index](#named-index-this-vault)), so they return the same results; the choice is about interface ergonomics and context cost.
1. **MCP tools (preferred when registered)** — `mcp__qmd__query`, `mcp__qmd__get`, `mcp__qmd__multi_get`, `mcp__qmd__status`. If these appear in your tool menu, the MCP server is live and pre-scoped to this vault. Call them directly — no `--index` argument needed, no shell involved, typed arguments. This is the intended path during a session.
2. **CLI fallback** — `qmd --index <name> query|search|vsearch|get|multi-get`. Use when the MCP server isn't registered (older vault clones, Windows install drift, disabled in `.mcp.json`), or for one-off shell checks outside a session. Always pass `--index <name>`.
@@ -19,22 +19,37 @@ Never fall through surfaces without cause — if MCP is registered, calling the
## Named Index (This Vault)
-This vault declares a **named QMD index** in `vault-manifest.json` under `qmd_index`. Every QMD command in this document uses `--index <name>` so queries, updates, and context strings stay scoped to this vault — not blended with any other vault that shares the machine.
+This vault uses a **named QMD index** so queries, updates, and context strings stay scoped to this vault — not blended with any other vault that shares the machine. Every QMD command in this document passes `--index <name>`.
-The MCP server (`.mcp.json`) and the SessionStart hook read the same field, so all three surfaces (CLI, MCP, hook) point at the same SQLite store.
+The name resolves the same way on all three surfaces (CLI, MCP, SessionStart hook), so they always point at the same SQLite store:
-**Read the index name from the manifest** before running commands. This snippet prints a clear error when the field is missing instead of silently running `qmd --index undefined`:
+1. `qmd_index` in `vault-manifest.json`, when set — an explicit pin.
+2. Otherwise the **vault folder name**, slugified. The template ships `qmd_index` empty so every install gets its own store without being asked a question.
+
+Pin the field if you want a name that survives renaming the vault folder, or want to keep a store you already built.
+
+**Read the resolved name** before running commands rather than assuming either branch:
```bash
INDEX=$(node -e '
+ const ok = (s) => typeof s === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(s);
const m = JSON.parse(require("fs").readFileSync("vault-manifest.json", "utf8"));
- if (!m.qmd_index) { process.stderr.write("qmd_index not set in vault-manifest.json\n"); process.exit(1); }
- process.stdout.write(m.qmd_index);
+ if (m.qmd_index && !ok(m.qmd_index)) {
+ process.stderr.write("qmd_index is set to an invalid name: " + JSON.stringify(m.qmd_index) + "\n");
+ process.exit(1);
+ }
+ const slug = require("path").basename(process.cwd()).normalize("NFKD").toLowerCase()
+ .replace(/[^a-z0-9._-]+/g, "-").replace(/-{2,}/g, "-").replace(/^[^a-z0-9]+|[-._]+$/g, "");
+ const name = [m.qmd_index, slug, m.template].find(ok);
+ if (!name) { process.stderr.write("no usable qmd index name — set qmd_index in vault-manifest.json\n"); process.exit(1); }
+ process.stdout.write(name);
') || exit 1
qmd --index "$INDEX" query "..."
```
-In-session, substitute the value of `qmd_index` directly in your commands (the index name is stable across the vault's lifetime). The default in a fresh template is `obsidian-mind`.
+The value is used as both a CLI argument and a filesystem path (`~/.cache/qmd/<name>.sqlite`), so an invalid pin must fail here rather than propagate — hence the explicit check instead of `m.qmd_index || slug`.
+
+In-session, substitute the resolved value directly in your commands — it is stable across the vault's lifetime unless the folder is renamed.
## Commands
@@ -62,7 +77,7 @@ The QMD SQLite store lives outside the repo (`~/.cache/qmd/<index>.sqlite`), so
node --experimental-strip-types .scripts/qmd-bootstrap.ts
```
-It reads `qmd_index` and `qmd_context` from `vault-manifest.json`, registers the collection, attaches the vault context, walks the vault, and generates embeddings. Idempotent — safe to re-run.
+It resolves the index name (pinned `qmd_index`, else the vault folder slug) and reads `qmd_context` from `vault-manifest.json`, registers the collection, attaches the vault context, walks the vault, and generates embeddings. Idempotent — safe to re-run.
## When to Search
diff --git a/.scripts/qmd-bootstrap.ts b/.scripts/qmd-bootstrap.ts
index cbd7868..355d290 100644
--- a/.scripts/qmd-bootstrap.ts
+++ b/.scripts/qmd-bootstrap.ts
@@ -51,7 +51,11 @@ import {
translateToGlob,
writeQmdIgnore,
} from "../.claude/scripts/lib/qmd-ignore.ts";
-import { isValidQmdIndex } from "../.claude/scripts/lib/session-start.ts";
+import {
+ deriveQmdIndex,
+ isValidQmdIndex,
+ resolveQmdIndex,
+} from "../.claude/scripts/lib/session-start.ts";
type ManifestSubset = {
readonly qmd_index?: string;
@@ -60,9 +64,17 @@ type ManifestSubset = {
readonly template?: string;
};
-function readManifest(): ManifestSubset | null {
+function readManifestRaw(): string | null {
+ try {
+ return readFileSync("vault-manifest.json", { encoding: "utf-8" });
+ } catch {
+ return null; /* handled by caller */
+ }
+}
+
+function parseManifest(raw: string | null): ManifestSubset | null {
+ if (raw === null) return null;
try {
- const raw = readFileSync("vault-manifest.json", { encoding: "utf-8" });
const parsed = JSON.parse(raw) as unknown;
if (parsed !== null && typeof parsed === "object") {
return parsed as ManifestSubset;
@@ -180,7 +192,8 @@ function runIdempotent(
}
function main(): void {
- const manifest = readManifest();
+ const manifestRaw = readManifestRaw();
+ const manifest = parseManifest(manifestRaw);
if (!manifest) {
process.stderr.write(
"vault-manifest.json missing or unreadable. Run from the vault root.\n",
@@ -188,22 +201,52 @@ function main(): void {
process.exit(1);
}
- const index = manifest.qmd_index;
- if (!index) {
+ // A non-empty `qmd_index` is an explicit pin and is taken literally — a
+ // typo there must fail loudly rather than silently fall through to a
+ // derived name, or the vault quietly indexes somewhere the user didn't ask
+ // for. Only an absent/empty field opts into derivation (#137).
+ const pinned = manifest.qmd_index;
+ if (pinned !== undefined && pinned !== "" && !isValidQmdIndex(pinned)) {
process.stderr.write(
- "vault-manifest.json has no `qmd_index` field. Add one before running the bootstrap.\n",
+ `vault-manifest.json \`qmd_index\` value ${JSON.stringify(pinned)} is not a valid index name.\n` +
+ "Allowed: alphanumerics, dot, dash, underscore; must start with an alphanumeric.\n" +
+ "(The value is used both in CLI argv and a filesystem path, so path separators and whitespace aren't accepted.)\n",
);
process.exit(1);
}
- if (!isValidQmdIndex(index)) {
+
+ // Route through the SAME resolver the read surfaces use rather than
+ // reimplementing the precedence here. This script WRITES the store; a
+ // private fallback would populate one index while SessionStart, the
+ // refresh worker, and the MCP wrapper read another — which surfaces as
+ // "0 documents", not as an error.
+ // `process.cwd()` is the vault root: `readManifest()` above already
+ // resolved `vault-manifest.json` relative to it, so a wrong cwd has
+ // already failed.
+ const index = resolveQmdIndex(manifestRaw, process.cwd());
+
+ if (index === null) {
process.stderr.write(
- `vault-manifest.json \`qmd_index\` value ${JSON.stringify(index)} is not a valid index name.\n` +
- "Allowed: alphanumerics, dot, dash, underscore; must start with an alphanumeric.\n" +
- "(The value is used both in CLI argv and a filesystem path, so path separators and whitespace aren't accepted.)\n",
+ "Could not determine a qmd index name for this vault.\n" +
+ "The vault folder name yields no usable slug and the manifest has no " +
+ "`template` to fall back on.\n" +
+ 'Set one explicitly: "qmd_index": "my-vault" in vault-manifest.json.\n',
);
process.exit(1);
}
+ // Reaching the `template` fallback means this vault shares a store with
+ // every other install that did the same — the exact collision #137 fixes.
+ // Keyed on derivation FAILING, not on the resolved name matching
+ // `template`: a vault whose folder legitimately slugifies to the template
+ // name is correctly isolated and must not be warned at.
+ if (!isValidQmdIndex(pinned) && deriveQmdIndex(process.cwd()) === null) {
+ warn(
+ `Vault folder name yields no usable index slug — falling back to the shared '${index}' index. ` +
+ 'Set "qmd_index" in vault-manifest.json to keep this vault\'s search store isolated.',
+ );
+ }
+
// Resolve once up front so every downstream spawn reuses the same entry.
const entry = resolveQmdEntry();
diff --git a/.shardmind/shard.yaml b/.shardmind/shard.yaml
index ae0c00a..776539a 100644
--- a/.shardmind/shard.yaml
+++ b/.shardmind/shard.yaml
@@ -31,7 +31,11 @@ hooks:
# v2 (v7.0.0): collection name derives from qmd_index with an in-place
# legacy-name migration, plus the qmd_min_version gate — upgrading
# installs must re-run bootstrap for the migration to execute.
- fingerprint: "qmd-v2"
+ # v3 (#137): qmd_index ships empty and the index name is derived from the
+ # vault folder, so two vaults on one machine stop sharing a store. An
+ # updating vault's index name changes, which means a new (empty) SQLite
+ # store — bootstrap must re-run to build it, or search returns nothing.
+ fingerprint: "qmd-v3"
personalize: .shardmind/hooks/personalize.ts
post-update: .shardmind/hooks/post-update.ts
# 60 s to accommodate first-run qmd bootstrap (index creation + initial embed pass).
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 89e42ea..b3e62f8 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -105,7 +105,7 @@ The `qmd_index` field is the most load-bearing. Three independent callers read i
```mermaid
flowchart LR
- Manifest["vault-manifest.json<br/>qmd_index: obsidian-mind"]
+ Manifest["vault-manifest.json<br/>qmd_index (or folder slug)"]
SessionStart["SessionStart hook<br/>(session-start.ts)"]
MCP[".mcp.json wrapper<br/>(qmd-mcp.mjs)"]
Refresh["Mid-session refresh<br/>(PostToolUse / Stop / PreCompact<br/>→ qmd-refresh-run.ts worker)"]
@@ -119,7 +119,7 @@ flowchart LR
MCP -->|search tools| Store
```
-Because all three callers derive the index name from the same field, the vault can coexist with other QMD-indexed projects on the same machine without collision. Change `qmd_index` in the manifest and the next bootstrap creates a fresh, isolated store.
+Because all three callers resolve the index name the same way — the `qmd_index` field when pinned, otherwise the vault folder name slugified — the vault coexists with other QMD-indexed projects on the same machine without collision. The template ships the field empty so two installs never share a store by default. Set `qmd_index` and the next bootstrap creates a fresh, isolated store under that name.
The `infrastructure[]` vs `user_content_roots[]` split is what makes `/om-vault-upgrade` work. When importing from an older template, the migrator overwrites infrastructure files wholesale and preserves user content untouched.
@@ -346,7 +346,7 @@ The design makes these changes easy:
| Change | Touch this |
|--------|------------|
| Add a new note type | `vault-manifest.json` → `frontmatter_required`, and a template in `templates/` |
-| Isolate this vault from others on the same machine | `vault-manifest.json` → `qmd_index`, then re-bootstrap |
+| Isolate this vault from others on the same machine | automatic (folder-derived); override with `vault-manifest.json` → `qmd_index`, then re-bootstrap |
| Add a new classification category | `.claude/scripts/classify-message.ts` + `CLAUDE.md` routing rules |
| Add a new lifecycle behavior | A new script in `.claude/scripts/` wired into all three agent configs |
| Add a new agent (Cursor, Windsurf, …) | New config file mapping events to existing scripts, optionally a new operating manual |
diff --git a/CLAUDE.md b/CLAUDE.md
index e878db2..0c506b8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -13,7 +13,7 @@ This vault has [obsidian-skills](https://github.com/kepano/obsidian-skills) inst
- **defuddle**: Extract clean markdown from web pages via `defuddle parse <url> --md`.
- **qmd**: Semantic search across the vault via [QMD](https://github.com/tobi/qmd). Use PROACTIVELY before reading files. **Preference order — pick the highest surface available and stop:**
1. **`mcp__qmd__query`, `mcp__qmd__get`, `mcp__qmd__multi_get`, `mcp__qmd__status`** — registered MCP tools. If you see them in your tool menu, they are live and pre-scoped to this vault's index. Use them first; no `--index` argument needed.
- 2. **`qmd --index <name> query|search|vsearch|get|multi-get`** — CLI fallback for one-off shell checks or when the MCP server is unavailable. Always pass `--index <name>` where `<name>` is the `qmd_index` field from `vault-manifest.json` so the SQLite store stays isolated from other vaults on the machine.
+ 2. **`qmd --index <name> query|search|vsearch|get|multi-get`** — CLI fallback for one-off shell checks or when the MCP server is unavailable. Always pass `--index <name>`, where `<name>` is the `qmd_index` field from `vault-manifest.json` when set and otherwise the vault folder name slugified, so the SQLite store stays isolated from other vaults on the machine.
3. **Grep / Glob / Read** — last resort, only when QMD is not installed at all.
The MCP server (`.mcp.json` → `.claude/scripts/qmd-mcp.mjs`), the CLI, and the SessionStart hook all read the same manifest field, so every surface scopes to the same store. On a fresh clone, run `node --experimental-strip-types .scripts/qmd-bootstrap.ts` once to build the index. Note: the MCP connect-time banner can read "0 documents" when the server registers before the SessionStart reindex finishes — a stale snapshot, not the dead-search state the self-heal guards; don't diagnose it.
diff --git a/README.ja.md b/README.ja.md
index 976de3d..1bf1280 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -132,7 +132,7 @@ npm install -g @tobilu/qmd
node --experimental-strip-types .scripts/qmd-bootstrap.ts
```
-ブートストラップは冪等で、再実行しても安全です。`vault-manifest.json` の `qmd_index` と `qmd_context` フィールドを読み取り、名前付きインデックスを登録してエンベディングを生成します(デフォルトのインデックス名は `obsidian-mind`)。SessionStart フック、`.mcp.json` のラッパー、CLI コマンドはすべて同じマニフェストフィールドを参照するため、同一マシン上の他のボールトと QMD データが混ざりません。CLI 実行時は常に `--index <名前>` を渡してください:
+ブートストラップは冪等で、再実行しても安全です。`vault-manifest.json` の `qmd_index` と `qmd_context` フィールドを読み取り、名前付きインデックスを登録してエンベディングを生成します(インデックス名は `qmd_index` が設定されていればその値、未設定ならボールトのフォルダ名をスラッグ化した値)。SessionStart フック、`.mcp.json` のラッパー、CLI コマンドはすべて同じマニフェストフィールドを参照するため、同一マシン上の他のボールトと QMD データが混ざりません。CLI 実行時は常に `--index <名前>` を渡してください:
```bash
qmd --index obsidian-mind query "キャッシュについて何を決めた?"
diff --git a/README.ko.md b/README.ko.md
index c771860..a3760d9 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -132,7 +132,7 @@ npm install -g @tobilu/qmd
node --experimental-strip-types .scripts/qmd-bootstrap.ts
```
-부트스트랩은 멱등성이 있어 재실행해도 안전합니다. `vault-manifest.json` 의 `qmd_index` 와 `qmd_context` 필드를 읽어 명명된 인덱스를 등록하고 임베딩을 생성합니다 (기본 인덱스 이름: `obsidian-mind`). SessionStart 훅, `.mcp.json` 래퍼, CLI 명령은 모두 동일한 매니페스트 필드를 참조하므로, 같은 머신의 다른 볼트와 QMD 데이터가 섞이지 않습니다. CLI 명령에는 항상 `--index <이름>` 을 전달하세요:
+부트스트랩은 멱등성이 있어 재실행해도 안전합니다. `vault-manifest.json` 의 `qmd_index` 와 `qmd_context` 필드를 읽어 명명된 인덱스를 등록하고 임베딩을 생성합니다 (인덱스 이름은 `qmd_index` 가 설정되어 있으면 그 값, 설정되어 있지 않으면 볼트 폴더 이름을 슬러그화한 값). SessionStart 훅, `.mcp.json` 래퍼, CLI 명령은 모두 동일한 매니페스트 필드를 참조하므로, 같은 머신의 다른 볼트와 QMD 데이터가 섞이지 않습니다. CLI 명령에는 항상 `--index <이름>` 을 전달하세요:
```bash
qmd --index obsidian-mind query "캐싱에 대해 뭘 결정했지?"
diff --git a/README.md b/README.md
index 90c775b..38d695b 100644
--- a/README.md
+++ b/README.md
@@ -136,7 +136,7 @@ npm install -g @tobilu/qmd
node --experimental-strip-types .scripts/qmd-bootstrap.ts
```
-The bootstrap is idempotent — safe to re-run. It reads the `qmd_index` and `qmd_context` fields from `vault-manifest.json` (default index name: `obsidian-mind`), registers the collection, attaches the context, and builds the index + embeddings. The SessionStart hook and `.mcp.json` wrapper both read the same manifest field, so CLI queries, the MCP server, and the re-index all scope to the same named SQLite store. This isolates the vault from any other QMD-using vault on the same machine.
+The bootstrap is idempotent — safe to re-run. It resolves this vault's index name — the `qmd_index` field from `vault-manifest.json` when set, otherwise the vault folder name slugified — reads `qmd_context`, registers the collection, attaches the context, and builds the index + embeddings. The SessionStart hook and `.mcp.json` wrapper both read the same manifest field, so CLI queries, the MCP server, and the re-index all scope to the same named SQLite store. This isolates the vault from any other QMD-using vault on the same machine.
If you want to use a different index name (for example, one vault per engineer on a shared workstation), edit `qmd_index` in `vault-manifest.json` before running the bootstrap. Once the store is populated, always pass `--index <name>` to the CLI:
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 9310198..705df48 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -132,7 +132,7 @@ npm install -g @tobilu/qmd
node --experimental-strip-types .scripts/qmd-bootstrap.ts
```
-引导脚本是幂等的,可以安全地重复运行。它读取 `vault-manifest.json` 中的 `qmd_index` 和 `qmd_context` 字段,注册命名索引并生成嵌入向量(默认索引名:`obsidian-mind`)。SessionStart 钩子、`.mcp.json` 封装脚本和 CLI 命令都读取同一个清单字段,因此同一台机器上的其他 vault 不会与本 vault 的 QMD 数据混淆。CLI 命令始终需要传递 `--index <名称>`:
+引导脚本是幂等的,可以安全地重复运行。它读取 `vault-manifest.json` 中的 `qmd_index` 和 `qmd_context` 字段,注册命名索引并生成嵌入向量(索引名为 `qmd_index` 的值;未设置时取 vault 文件夹名的 slug)。SessionStart 钩子、`.mcp.json` 封装脚本和 CLI 命令都读取同一个清单字段,因此同一台机器上的其他 vault 不会与本 vault 的 QMD 数据混淆。CLI 命令始终需要传递 `--index <名称>`:
```bash
qmd --index obsidian-mind query "我们关于缓存做了什么决策"
diff --git a/brain/Skills.md b/brain/Skills.md
index a802d8f..7575a92 100644
--- a/brain/Skills.md
+++ b/brain/Skills.md
@@ -109,7 +109,7 @@ Subagents run in isolated context windows via `.claude/agents/`. They don't poll
## Semantic Search (QMD)
-If QMD is installed (`npm install -g @tobilu/qmd`), the vault has semantic search. Every command takes `--index <name>` where `<name>` is `vault-manifest.json`'s `qmd_index` field (default: `obsidian-mind`):
+If QMD is installed (`npm install -g @tobilu/qmd`), the vault has semantic search. Every command takes `--index <name>`, where `<name>` is `vault-manifest.json`'s `qmd_index` field when set and otherwise the vault folder name slugified:
- `qmd --index <name> query "..."` — hybrid BM25 + vector + LLM reranking (best quality)
- `qmd --index <name> search "..."` — fast BM25 keyword search
diff --git a/vault-manifest.json b/vault-manifest.json
index 4b0e40f..58a19ec 100644
--- a/vault-manifest.json
+++ b/vault-manifest.json
@@ -2,7 +2,7 @@
"template": "obsidian-mind",
"version": "7.0.1",
"released": "2026-07-24",
- "qmd_index": "obsidian-mind",
+ "qmd_index": "",
"qmd_min_version": "2.0.0",
"open_loop_dirs": [
"work/1-1",