Skip to content

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

feat: per-vault QMD named index, manifest-driven context, bootstrap (#59)

Brenno Ferrarid2e3fb743798
diff --git a/.claude/scripts/lib/qmd.ts b/.claude/scripts/lib/qmd.ts
new file mode 100644
index 0000000..bc15d23
--- /dev/null
+++ b/.claude/scripts/lib/qmd.ts
@@ -0,0 +1,81 @@
+/**
+ * Cross-platform QMD invocation helpers.
+ *
+ * Bare `spawnSync("qmd", ...)` fails on Windows because npm installs qmd as a
+ * .cmd/.ps1 shim that Node's spawn can't resolve without routing through the
+ * platform shell — and even with `shell: true` the .cmd shim itself depends
+ * on /bin/sh via %_prog%, which fails on stock Windows without Git Bash.
+ *
+ * Rather than scatter platform-conditional `shell: process.platform === "win32"`
+ * flags across every qmd call, these helpers resolve @tobilu/qmd's real JS
+ * entry and let callers spawn it with the current Node binary. No shell, no
+ * shim, same code path on Windows, macOS, and Linux.
+ *
+ * Shared with `.claude/scripts/qmd-mcp.mjs` by duplicated implementation —
+ * that file is .mjs (MCP servers run as their own entry), so it can't import
+ * this .ts helper at Node's `--experimental-strip-types` runtime. The two
+ * copies are asserted independently: `tests/qmd.test.ts` locks this file's
+ * `resolveQmdEntry` + `buildQmdCommand` shape, and `tests/qmd-mcp.test.ts`
+ * locks the .mjs wrapper's equivalents. Drift between the two shows up as
+ * a test failure on the CI matrix rather than a silent platform bug.
+ */
+
+import { spawnSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import { createRequire } from "node:module";
+import { isAbsolute, join } from "node:path";
+
+const require = createRequire(import.meta.url);
+
+/**
+ * Locate @tobilu/qmd's real JS entrypoint. Returns an absolute path when
+ * resolvable, null when not. A null return signals the caller to fall back
+ * to invoking `qmd` directly via the platform shell (last-resort path for
+ * non-npm installs).
+ */
+export function resolveQmdEntry(): string | null {
+ try {
+ return require.resolve("@tobilu/qmd/dist/cli/qmd.js");
+ } catch {}
+
+ // Fallback for global npm installs that aren't on this package's resolution
+ // path — ask npm directly where global packages live. Bounded timeout so a
+ // hung npm process can't block a fire-and-forget hook indefinitely.
+ const npmRoot = spawnSync("npm", ["root", "-g"], {
+ shell: true,
+ encoding: "utf8",
+ timeout: 3000,
+ });
+ if (npmRoot.error || npmRoot.signal !== null || npmRoot.status !== 0) {
+ return null;
+ }
+
+ const root = (npmRoot.stdout ?? "").trim();
+ if (root === "" || !isAbsolute(root)) return null;
+
+ const entry = join(root, "@tobilu", "qmd", "dist", "cli", "qmd.js");
+ return existsSync(entry) ? entry : null;
+}
+
+/**
+ * Build the (command, args, shell) tuple for a qmd invocation. When an
+ * entrypoint resolves, `process.execPath` runs it directly with no shell
+ * (identical on every platform). When it doesn't, fall back to `qmd` via
+ * the platform shell — best-effort for non-npm installs.
+ */
+export function buildQmdCommand(
+ entry: string | null,
+ subcommandArgs: readonly string[],
+): {
+ readonly cmd: string;
+ readonly args: readonly string[];
+ readonly shell: boolean;
+} {
+ return entry !== null
+ ? {
+ cmd: process.execPath,
+ args: [entry, ...subcommandArgs],
+ shell: false,
+ }
+ : { cmd: "qmd", args: [...subcommandArgs], shell: true };
+}
diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.ts
index 53007af..9a6e88f 100644
--- a/.claude/scripts/lib/session-start.ts
+++ b/.claude/scripts/lib/session-start.ts
@@ -143,6 +143,67 @@ export function hasBrainContent(body: string): boolean {
return /^[ \t]*[-*+][ \t]+\S.*$/m.test(body);
}
+/**
+ * Restricted character set for `qmd_index`. The value ends up in both CLI
+ * argv and a filesystem path (`~/.cache/qmd/<name>.sqlite`), so path
+ * separators, parent-dir refs, whitespace, and shell metacharacters must
+ * not be accepted. Mirrors the shape of npm package names / git branch
+ * segments: alnum + dot + dash + underscore, must start with an alnum.
+ */
+const QMD_INDEX_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
+
+/**
+ * True when `value` is a string that's safe to use as a qmd named index.
+ * Exported so callers that read the manifest from other surfaces (the MCP
+ * wrapper, the bootstrap script) can apply the same rule.
+ */
+export function isValidQmdIndex(value: unknown): value is string {
+ return typeof value === "string" && QMD_INDEX_PATTERN.test(value);
+}
+
+/**
+ * Extract the `qmd_index` string from a `vault-manifest.json` source. Returns
+ * the configured named index (so QMD's storage is scoped to this vault) or
+ * null when the manifest is absent, malformed, missing the field, or the
+ * value fails validation (path separators, whitespace, empty, etc.).
+ *
+ * Kept as a pure helper so the caller can own the fs read and tests can pass
+ * fixture strings. A null return means "use QMD's default global index" —
+ * backwards-compatible with forks that haven't adopted the field yet.
+ */
+export function parseQmdIndex(manifestJson: string | null): string | null {
+ if (manifestJson === null) return null;
+ try {
+ const parsed = JSON.parse(manifestJson) as unknown;
+ if (
+ parsed !== null &&
+ typeof parsed === "object" &&
+ "qmd_index" in parsed
+ ) {
+ const value = (parsed as Record<string, unknown>)["qmd_index"];
+ if (isValidQmdIndex(value)) return value;
+ }
+ } catch {
+ /* malformed manifest → treat as missing */
+ }
+ return null;
+}
+
+/**
+ * Build the argv tail for a `qmd` CLI invocation, prepending `--index <name>`
+ * when the vault has configured a named index. Callers pass the subcommand
+ * and its args (e.g. `["update"]`, `["query", text, "--json"]`); the return
+ * value is the full argv after the `qmd` command itself.
+ */
+export function qmdArgsWithIndex(
+ index: string | null,
+ subcommandArgs: readonly string[],
+): string[] {
+ return index === null
+ ? [...subcommandArgs]
+ : ["--index", index, ...subcommandArgs];
+}
+
/**
* Format the "Brain Topics" section — one line per brain/ note with its
* description from frontmatter, so Claude sees what topic notes exist
diff --git a/.claude/scripts/qmd-mcp.d.mts b/.claude/scripts/qmd-mcp.d.mts
index c1c0723..d011953 100644
--- a/.claude/scripts/qmd-mcp.d.mts
+++ b/.claude/scripts/qmd-mcp.d.mts
@@ -10,12 +10,41 @@
*/
export function resolveQmdEntry(): string | null;
+/**
+ * Resolve the vault root directory from a `file://` URL and optional env.
+ * The env argument is read for `CLAUDE_PROJECT_DIR` (Claude Code's
+ * project-dir signal); when absent, the root is computed from the URL.
+ */
+export function resolveVaultRoot(
+ metaUrl: string,
+ env?: NodeJS.ProcessEnv,
+): string;
+
+/**
+ * Extract the `qmd_index` string from a vault-manifest.json source.
+ * Returns the named index or null when absent, malformed, or empty.
+ */
+export function readQmdIndex(manifestJson: string | null): 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.
+ */
+export function resolveIndexSqlitePath(
+ indexName: string,
+ env: NodeJS.ProcessEnv,
+ home: string,
+): string;
+
/**
* Build the (command, args, shell) tuple the spawn layer should invoke.
+ * When `qmdIndex` is a non-empty string, `--index <name>` is prepended to
+ * the mcp subcommand.
*/
export function buildLaunchCommand(
entry: string | null,
extraArgs?: readonly string[],
+ qmdIndex?: string | null,
): {
readonly cmd: string;
readonly args: readonly string[];
diff --git a/.claude/scripts/qmd-mcp.mjs b/.claude/scripts/qmd-mcp.mjs
index bc62087..fda5237 100644
--- a/.claude/scripts/qmd-mcp.mjs
+++ b/.claude/scripts/qmd-mcp.mjs
@@ -2,28 +2,57 @@
/**
* qmd-mcp.mjs — cross-platform MCP launcher for QMD.
*
- * Claude Code spawns MCP servers without a shell, so on Windows the npm-installed
- * `qmd` shim (a .cmd/.ps1 file) can't be located from `child_process.spawn`. Even
- * with shell: true, the shim itself delegates to /bin/sh via %_prog%, which fails
- * on stock Windows without Git Bash's sh.exe on PATH.
+ * Does three things no bare `qmd mcp` invocation can do:
*
- * This wrapper bypasses the shim by resolving @tobilu/qmd's real JS entrypoint
- * and spawning it with the current Node binary. Works identically on Windows,
- * macOS, and Linux — no shell, no /bin/sh dependency.
+ * 1. Bypass the Windows .cmd/.ps1 shim. Claude Code spawns MCP servers
+ * without a shell, and even `shell: true` isn't enough: the shim
+ * delegates to /bin/sh via %_prog%, which fails on stock Windows without
+ * Git Bash's sh.exe on PATH. We resolve @tobilu/qmd/dist/cli/qmd.js and
+ * spawn it with the current Node binary — no shell, no shim, same code
+ * path on every platform.
*
- * Fallback: if @tobilu/qmd isn't resolvable from this location (e.g., the user
- * has qmd installed via a non-npm channel), fall through to the `qmd` command
- * with shell: true so the global shim is still attempted.
+ * 2. Scope the MCP server to this vault's named index. If vault-manifest.json
+ * declares a `qmd_index`, pass `--index <name>` so the MCP reads the same
+ * SQLite store as the SessionStart hook and the CLI.
+ *
+ * 3. Work around a qmd 2.1.0 bug. `qmd --index <name> mcp` currently ignores
+ * the --index flag (mcp/server.js calls getDefaultDbPath() without the
+ * configured name). Setting INDEX_PATH forces the correct SQLite path
+ * regardless — store.js honors INDEX_PATH unconditionally. We keep
+ * --index on argv too so a future qmd fix works without a wrapper change.
+ *
+ * Fallback: if @tobilu/qmd isn't resolvable, fall through to a bare `qmd`
+ * command with shell: true so non-npm installations still have a chance to
+ * work. When an index is configured, the INDEX_PATH env var still applies.
*/
import { spawn, spawnSync } from "node:child_process";
-import { existsSync } from "node:fs";
-import { isAbsolute, join } from "node:path";
+import { existsSync, readFileSync } from "node:fs";
+import { dirname, isAbsolute, join, resolve } from "node:path";
import { createRequire } from "node:module";
-import { pathToFileURL } from "node:url";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { homedir } from "node:os";
const require = createRequire(import.meta.url);
+/**
+ * Resolve the wrapper's vault root from a `file://` URL and optional env
+ * override. Kept as a pure helper (both inputs passed in) so tests can lock
+ * the path math without depending on the current process's working directory
+ * or CLAUDE_PROJECT_DIR. Layout assumption: the wrapper lives at
+ * `<vault>/.claude/scripts/qmd-mcp.mjs`, so the vault root is two levels up.
+ */
+export function resolveVaultRoot(metaUrl, env = process.env) {
+ const envRoot = env["CLAUDE_PROJECT_DIR"];
+ if (envRoot && isAbsolute(envRoot)) return envRoot;
+ return resolve(dirname(fileURLToPath(metaUrl)), "..", "..");
+}
+
+// Resolved once at module load. Manifest lookups use this instead of the
+// current working directory, so a drifted MCP-host CWD can't silently break
+// per-vault isolation.
+const VAULT_ROOT = resolveVaultRoot(import.meta.url);
+
/**
* Locate @tobilu/qmd's real JS entrypoint. Returns an absolute path when
* resolvable, null when not. Exported so the cross-platform test matrix can
@@ -64,22 +93,96 @@ export function resolveQmdEntry() {
}
/**
- * Build the (command, args) tuple the spawn layer should invoke. Split out
- * so tests can lock both branches (resolved entrypoint vs. PATH fallback)
- * without running a real child.
+ * Restricted character set for `qmd_index`. Duplicated from
+ * `lib/session-start.ts:QMD_INDEX_PATTERN` (this file is .mjs and can't
+ * import from the .ts lib at strip-types runtime). The shape is asserted
+ * by the tests — alnum + dot + dash + underscore, must start with alnum.
+ * Rejects path separators, parent-dir refs, whitespace, empty strings.
+ */
+const QMD_INDEX_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
+
+/**
+ * Extract the `qmd_index` string from a vault-manifest.json source. Returns
+ * the configured named index (so QMD's storage is scoped to this vault) or
+ * null when the manifest is absent, malformed, missing the field, or the
+ * value fails validation.
+ *
+ * Kept as a pure helper so tests can pass fixture strings. A null return
+ * means "use QMD's default global index" — backwards-compatible with forks
+ * that haven't adopted the field yet.
*/
-export function buildLaunchCommand(entry, extraArgs = []) {
- const qmdArgs = ["mcp", ...extraArgs];
+export function readQmdIndex(manifestJson) {
+ if (manifestJson === null) return null;
+ try {
+ const parsed = JSON.parse(manifestJson);
+ if (
+ parsed !== null &&
+ typeof parsed === "object" &&
+ typeof parsed.qmd_index === "string" &&
+ QMD_INDEX_PATTERN.test(parsed.qmd_index)
+ ) {
+ return parsed.qmd_index;
+ }
+ } catch {
+ /* malformed manifest → treat as missing */
+ }
+ return null;
+}
+
+/**
+ * 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 +
+ * qmd/<indexName>.sqlite). Exported so tests can lock the platform-neutral
+ * behavior — qmd uses this same logic on Linux, macOS, and Windows with no
+ * per-platform branch.
+ */
+export function resolveIndexSqlitePath(indexName, env, home) {
+ const base = env["XDG_CACHE_HOME"] ?? join(home, ".cache");
+ return join(base, "qmd", `${indexName}.sqlite`);
+}
+
+/**
+ * Build the (command, args, shell) tuple the spawn layer should invoke.
+ * When `qmdIndex` is a non-empty string, `--index <name>` is prepended to
+ * the mcp subcommand; otherwise the invocation matches the pre-per-vault
+ * shape for backward compatibility.
+ */
+export function buildLaunchCommand(entry, extraArgs = [], qmdIndex = null) {
+ const mcpArgs = qmdIndex ? ["--index", qmdIndex, "mcp"] : ["mcp"];
+ const qmdArgs = [...mcpArgs, ...extraArgs];
return entry
? { cmd: process.execPath, args: [entry, ...qmdArgs], shell: false }
: { cmd: "qmd", args: qmdArgs, shell: true };
}
+function readManifestRaw() {
+ try {
+ return readFileSync(join(VAULT_ROOT, "vault-manifest.json"), {
+ encoding: "utf-8",
+ });
+ } catch {
+ return null;
+ }
+}
+
function runAsMcp() {
+ const qmdIndex = readQmdIndex(readManifestRaw());
+
+ if (qmdIndex && !process.env["INDEX_PATH"]) {
+ // Apply the qmd 2.1.0 MCP bug workaround: pin the SQLite store to the
+ // named index. Don't clobber a user-supplied INDEX_PATH.
+ process.env["INDEX_PATH"] = resolveIndexSqlitePath(
+ qmdIndex,
+ process.env,
+ homedir(),
+ );
+ }
+
const entry = resolveQmdEntry();
const { cmd, args, shell } = buildLaunchCommand(
entry,
process.argv.slice(2),
+ qmdIndex,
);
const child = spawn(cmd, args, { stdio: "inherit", shell });
@@ -112,8 +215,8 @@ function runAsMcp() {
}
// Only spawn a child when this file is the actual entry point. Importing it
-// from tests (to exercise resolveQmdEntry / buildLaunchCommand in isolation)
-// must not trigger a spawn.
+// from tests (to exercise the pure helpers in isolation) must not trigger a
+// spawn.
const entryUrl = process.argv[1]
? pathToFileURL(process.argv[1]).href
: null;
diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.ts
index 133e820..9dd9538 100644
--- a/.claude/scripts/session-start.ts
+++ b/.claude/scripts/session-start.ts
@@ -27,7 +27,18 @@ import {
formatBrainIndex,
stripFrontmatter,
hasBrainContent,
+ parseQmdIndex,
+ qmdArgsWithIndex,
} from "./lib/session-start.ts";
+import { buildQmdCommand, resolveQmdEntry } from "./lib/qmd.ts";
+
+function readManifestRaw(): string | null {
+ try {
+ return readFileSync("vault-manifest.json", { encoding: "utf-8" });
+ } catch {
+ return null;
+ }
+}
const cwd =
process.env["CLAUDE_PROJECT_DIR"] ??
@@ -47,7 +58,23 @@ if (envFile) {
}
// Incremental QMD re-index. Fire-and-forget; ignore failures (qmd is optional).
-spawnSync("qmd", ["update"], { stdio: "ignore", timeout: 30_000 });
+// Scope to this vault's named index when the manifest declares one, so vaults
+// sharing a machine don't blend results in QMD's default global index. Falls
+// back silently for forks that haven't adopted the `qmd_index` manifest field.
+//
+// Route through `buildQmdCommand` so the same shim-bypass logic that fixes
+// the MCP wrapper applies here too — `node qmd.js update` runs identically
+// on Windows, macOS, and Linux; no platform conditionals.
+const qmdIndex = parseQmdIndex(readManifestRaw());
+const qmdUpdate = buildQmdCommand(
+ resolveQmdEntry(),
+ qmdArgsWithIndex(qmdIndex, ["update"]),
+);
+spawnSync(qmdUpdate.cmd, qmdUpdate.args as string[], {
+ stdio: "ignore",
+ timeout: 30_000,
+ shell: qmdUpdate.shell,
+});
type CmdResult =
| { readonly kind: "ok"; readonly stdout: string }
diff --git a/.claude/scripts/tests/qmd-mcp.test.ts b/.claude/scripts/tests/qmd-mcp.test.ts
index f63b52c..e2f9a4e 100644
--- a/.claude/scripts/tests/qmd-mcp.test.ts
+++ b/.claude/scripts/tests/qmd-mcp.test.ts
@@ -23,6 +23,9 @@ import { isAbsolute } from "node:path";
import {
resolveQmdEntry,
buildLaunchCommand,
+ readQmdIndex,
+ resolveIndexSqlitePath,
+ resolveVaultRoot,
} from "../qmd-mcp.mjs";
describe("resolveQmdEntry", () => {
@@ -84,4 +87,158 @@ describe("buildLaunchCommand", () => {
const { args } = buildLaunchCommand(null, ["--debug"]);
assert.deepEqual(args, ["mcp", "--debug"]);
});
+
+ test("prepends --index <name> when a qmdIndex is provided (resolved branch)", () => {
+ const { args } = buildLaunchCommand("/fake/qmd.js", [], "obsidian-mind");
+ assert.deepEqual(args, [
+ "/fake/qmd.js",
+ "--index",
+ "obsidian-mind",
+ "mcp",
+ ]);
+ });
+
+ test("prepends --index <name> when a qmdIndex is provided (fallback branch)", () => {
+ const { args } = buildLaunchCommand(null, [], "my-vault");
+ assert.deepEqual(args, ["--index", "my-vault", "mcp"]);
+ });
+
+ test("qmdIndex + extra argv compose correctly", () => {
+ const { args } = buildLaunchCommand(
+ "/fake/qmd.js",
+ ["--verbose"],
+ "vault-a",
+ );
+ assert.deepEqual(args, [
+ "/fake/qmd.js",
+ "--index",
+ "vault-a",
+ "mcp",
+ "--verbose",
+ ]);
+ });
+});
+
+describe("readQmdIndex", () => {
+ test("extracts qmd_index when present as a non-empty string", () => {
+ const manifest = JSON.stringify({ qmd_index: "obsidian-mind" });
+ assert.equal(readQmdIndex(manifest), "obsidian-mind");
+ });
+ test("returns null when qmd_index is an empty string", () => {
+ assert.equal(readQmdIndex(JSON.stringify({ qmd_index: "" })), null);
+ });
+ test("returns null when qmd_index is missing from the manifest", () => {
+ assert.equal(readQmdIndex(JSON.stringify({ template: "obsidian-mind" })), null);
+ });
+ test("returns null when qmd_index is not a string", () => {
+ assert.equal(readQmdIndex(JSON.stringify({ qmd_index: 42 })), null);
+ });
+ test("returns null when manifest source is null (missing file)", () => {
+ assert.equal(readQmdIndex(null), null);
+ });
+ test("returns null when manifest is malformed JSON", () => {
+ assert.equal(readQmdIndex("{ not json"), null);
+ });
+ test("returns null when manifest parses to a non-object", () => {
+ assert.equal(readQmdIndex('"just a string"'), null);
+ });
+ test("returns null when qmd_index contains path separators (/ or \\)", () => {
+ assert.equal(
+ readQmdIndex(JSON.stringify({ qmd_index: "vault/sub" })),
+ null,
+ );
+ assert.equal(
+ readQmdIndex(JSON.stringify({ qmd_index: "vault\\sub" })),
+ null,
+ );
+ });
+ test("returns null when qmd_index is a parent-dir escape", () => {
+ assert.equal(
+ readQmdIndex(JSON.stringify({ qmd_index: "../etc" })),
+ null,
+ );
+ });
+ test("returns null when qmd_index contains whitespace", () => {
+ assert.equal(
+ readQmdIndex(JSON.stringify({ qmd_index: "my vault" })),
+ null,
+ );
+ });
+ test("returns null when qmd_index starts with non-alphanumeric", () => {
+ assert.equal(
+ readQmdIndex(JSON.stringify({ qmd_index: "-lead" })),
+ null,
+ );
+ });
+ test("accepts dash, dot, and underscore inside the name", () => {
+ assert.equal(
+ readQmdIndex(JSON.stringify({ qmd_index: "vault.2_a-b" })),
+ "vault.2_a-b",
+ );
+ });
+});
+
+describe("resolveVaultRoot", () => {
+ test("uses CLAUDE_PROJECT_DIR when set to an absolute path", () => {
+ const out = resolveVaultRoot(
+ "file:///some/vault/.claude/scripts/qmd-mcp.mjs",
+ { CLAUDE_PROJECT_DIR: "/override/root" },
+ );
+ assert.equal(out, "/override/root");
+ });
+
+ test("ignores CLAUDE_PROJECT_DIR when value is empty", () => {
+ const out = resolveVaultRoot(
+ "file:///C:/vault/.claude/scripts/qmd-mcp.mjs",
+ { CLAUDE_PROJECT_DIR: "" },
+ );
+ // Path math: two levels up from .claude/scripts/qmd-mcp.mjs → vault/
+ assert.match(out, /[\\/]vault$/, `expected vault-root shape, got: ${out}`);
+ });
+
+ test("ignores CLAUDE_PROJECT_DIR when value is a relative path (not trusted)", () => {
+ const out = resolveVaultRoot(
+ "file:///C:/vault/.claude/scripts/qmd-mcp.mjs",
+ { CLAUDE_PROJECT_DIR: "relative/thing" },
+ );
+ assert.match(out, /[\\/]vault$/);
+ });
+
+ test("derives the vault root from import.meta.url when env is unset", () => {
+ // `fileURLToPath` requires a drive-letter prefix on Windows but not on
+ // POSIX. Pick an OS-appropriate fixture so the assertion — that the
+ // result walks two levels up from .claude/scripts/qmd-mcp.mjs — runs
+ // on every matrix leg.
+ const url =
+ process.platform === "win32"
+ ? "file:///C:/home/me/my-vault/.claude/scripts/qmd-mcp.mjs"
+ : "file:///home/me/my-vault/.claude/scripts/qmd-mcp.mjs";
+ const out = resolveVaultRoot(url, {});
+ assert.match(out, /[\\/]my-vault$/);
+ });
+});
+
+describe("resolveIndexSqlitePath", () => {
+ test("joins XDG_CACHE_HOME + qmd + <name>.sqlite when the env var is set", () => {
+ const out = resolveIndexSqlitePath(
+ "vault-a",
+ { XDG_CACHE_HOME: "/custom/cache" },
+ "/home/user",
+ );
+ assert.match(out, /[\\/]custom[\\/]cache[\\/]qmd[\\/]vault-a\.sqlite$/);
+ });
+ test("falls back to <home>/.cache/qmd/<name>.sqlite when XDG_CACHE_HOME is unset", () => {
+ const out = resolveIndexSqlitePath("my-vault", {}, "/home/user");
+ assert.match(out, /[\\/]home[\\/]user[\\/]\.cache[\\/]qmd[\\/]my-vault\.sqlite$/);
+ });
+ test("matches qmd's own getDefaultDbPath rule on all platforms (no Library/Caches, no AppData branch)", () => {
+ // This locks the contract: our INDEX_PATH override must point at the same
+ // file qmd's CLI would write to without the override. Regression here
+ // would mean MCP and CLI disagree about the store location.
+ const home = "/Users/test";
+ const out = resolveIndexSqlitePath("vault", {}, home);
+ assert.match(out, /[\\/]Users[\\/]test[\\/]\.cache[\\/]qmd[\\/]vault\.sqlite$/);
+ assert.doesNotMatch(out, /Library[\\/]Caches/);
+ assert.doesNotMatch(out, /AppData/);
+ });
});
diff --git a/.claude/scripts/tests/qmd.test.ts b/.claude/scripts/tests/qmd.test.ts
new file mode 100644
index 0000000..d977594
--- /dev/null
+++ b/.claude/scripts/tests/qmd.test.ts
@@ -0,0 +1,93 @@
+/**
+ * Tests for the shared cross-platform qmd spawn helpers.
+ *
+ * Paired with `tests/qmd-mcp.test.ts` — the MCP wrapper duplicates this
+ * logic in .mjs (because .ts imports don't flow from .mjs at strip-types
+ * runtime). Both copies are exercised in the CI matrix so drift between
+ * them surfaces as a test failure rather than a silent platform bug.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync } from "node:fs";
+import { isAbsolute } from "node:path";
+
+import { buildQmdCommand, resolveQmdEntry } from "../lib/qmd.ts";
+
+describe("lib/qmd.resolveQmdEntry", () => {
+ test("returns an absolute path to an existing qmd entrypoint when qmd is installed", () => {
+ const entry = resolveQmdEntry();
+
+ // When qmd isn't on this machine, the resolver must cleanly return null
+ // — the assertion below is meaningful only against a real install.
+ // CI installs qmd globally, so the positive branch runs on every
+ // matrix leg.
+ if (entry === null) {
+ assert.ok(
+ true,
+ "qmd not installed in this environment — resolver correctly returned null",
+ );
+ return;
+ }
+
+ assert.equal(typeof entry, "string");
+ assert.equal(
+ isAbsolute(entry),
+ true,
+ `resolved path must be absolute, got: ${entry}`,
+ );
+ assert.equal(
+ existsSync(entry),
+ true,
+ `resolved path must exist on disk, got: ${entry}`,
+ );
+ assert.match(
+ entry,
+ /@tobilu[\\/]qmd[\\/]dist[\\/]cli[\\/]qmd\.js$/,
+ `resolved path should point at @tobilu/qmd's CLI entry, got: ${entry}`,
+ );
+ });
+});
+
+describe("lib/qmd.buildQmdCommand", () => {
+ test("routes through process.execPath when an entrypoint is resolved", () => {
+ const out = buildQmdCommand("/fake/qmd.js", ["update"]);
+ assert.equal(out.cmd, process.execPath);
+ assert.deepEqual(out.args, ["/fake/qmd.js", "update"]);
+ assert.equal(out.shell, false);
+ });
+
+ test("forwards multi-arg subcommands", () => {
+ const out = buildQmdCommand("/fake/qmd.js", [
+ "--index",
+ "vault-a",
+ "query",
+ "hello",
+ ]);
+ assert.deepEqual(out.args, [
+ "/fake/qmd.js",
+ "--index",
+ "vault-a",
+ "query",
+ "hello",
+ ]);
+ });
+
+ test("falls back to bare `qmd` with shell: true when resolution returns null", () => {
+ const out = buildQmdCommand(null, ["update"]);
+ assert.equal(out.cmd, "qmd");
+ assert.deepEqual(out.args, ["update"]);
+ assert.equal(out.shell, true);
+ });
+
+ test("fallback forwards multi-arg subcommands", () => {
+ const out = buildQmdCommand(null, ["--index", "vault-a", "embed"]);
+ assert.deepEqual(out.args, ["--index", "vault-a", "embed"]);
+ });
+
+ test("returns a fresh args array (does not alias the input)", () => {
+ const input = ["update"];
+ const out = buildQmdCommand(null, input);
+ assert.notEqual(out.args, input);
+ });
+});
diff --git a/.claude/scripts/tests/session-start.test.ts b/.claude/scripts/tests/session-start.test.ts
index 8b9c0e3..cef35e7 100644
--- a/.claude/scripts/tests/session-start.test.ts
+++ b/.claude/scripts/tests/session-start.test.ts
@@ -17,6 +17,9 @@ import {
formatBrainIndex,
stripFrontmatter,
hasBrainContent,
+ parseQmdIndex,
+ qmdArgsWithIndex,
+ isValidQmdIndex,
} from "../lib/session-start.ts";
describe("take", () => {
@@ -191,6 +194,111 @@ describe("hasBrainContent", () => {
});
});
+describe("parseQmdIndex", () => {
+ test("extracts qmd_index when present as a non-empty string", () => {
+ const manifest = JSON.stringify({ qmd_index: "obsidian-mind" });
+ assert.equal(parseQmdIndex(manifest), "obsidian-mind");
+ });
+ test("returns null when qmd_index is an empty string", () => {
+ const manifest = JSON.stringify({ qmd_index: "" });
+ assert.equal(parseQmdIndex(manifest), null);
+ });
+ test("returns null when qmd_index is missing from the manifest", () => {
+ const manifest = JSON.stringify({ template: "obsidian-mind" });
+ assert.equal(parseQmdIndex(manifest), null);
+ });
+ test("returns null when qmd_index is not a string", () => {
+ const manifest = JSON.stringify({ qmd_index: 42 });
+ assert.equal(parseQmdIndex(manifest), null);
+ });
+ test("returns null when the manifest source is null (missing file)", () => {
+ assert.equal(parseQmdIndex(null), null);
+ });
+ test("returns null when the manifest is malformed JSON", () => {
+ assert.equal(parseQmdIndex("{ not json"), null);
+ });
+ test("returns null when the manifest parses to a non-object", () => {
+ assert.equal(parseQmdIndex('"just a string"'), null);
+ });
+ test("returns null when qmd_index contains a forward-slash path separator", () => {
+ const manifest = JSON.stringify({ qmd_index: "vault/subdir" });
+ assert.equal(parseQmdIndex(manifest), null);
+ });
+ test("returns null when qmd_index contains a backslash path separator", () => {
+ const manifest = JSON.stringify({ qmd_index: "vault\\subdir" });
+ assert.equal(parseQmdIndex(manifest), null);
+ });
+ test("returns null when qmd_index is a parent-dir escape attempt", () => {
+ const manifest = JSON.stringify({ qmd_index: "../../etc/passwd" });
+ assert.equal(parseQmdIndex(manifest), null);
+ });
+ test("returns null when qmd_index contains whitespace", () => {
+ const manifest = JSON.stringify({ qmd_index: "my vault" });
+ assert.equal(parseQmdIndex(manifest), null);
+ });
+ test("returns null when qmd_index is whitespace-only", () => {
+ const manifest = JSON.stringify({ qmd_index: " " });
+ assert.equal(parseQmdIndex(manifest), null);
+ });
+ test("returns null when qmd_index starts with a non-alphanumeric character", () => {
+ const manifest = JSON.stringify({ qmd_index: "-leading-dash" });
+ assert.equal(parseQmdIndex(manifest), null);
+ });
+ test("accepts dash, dot, and underscore inside the name", () => {
+ const manifest = JSON.stringify({ qmd_index: "vault-a_b.2" });
+ assert.equal(parseQmdIndex(manifest), "vault-a_b.2");
+ });
+});
+
+describe("isValidQmdIndex", () => {
+ test("accepts standard names", () => {
+ assert.equal(isValidQmdIndex("obsidian-mind"), true);
+ assert.equal(isValidQmdIndex("vigil"), true);
+ assert.equal(isValidQmdIndex("vault.2_final"), true);
+ });
+ test("rejects path separators, whitespace, empty, and leading punctuation", () => {
+ assert.equal(isValidQmdIndex(""), false);
+ assert.equal(isValidQmdIndex(" "), false);
+ assert.equal(isValidQmdIndex("a b"), false);
+ assert.equal(isValidQmdIndex("a/b"), false);
+ assert.equal(isValidQmdIndex("a\\b"), false);
+ assert.equal(isValidQmdIndex("../x"), false);
+ assert.equal(isValidQmdIndex("-leading"), false);
+ assert.equal(isValidQmdIndex(".leading"), false);
+ });
+ test("rejects non-string values", () => {
+ assert.equal(isValidQmdIndex(undefined), false);
+ assert.equal(isValidQmdIndex(null), false);
+ assert.equal(isValidQmdIndex(42), false);
+ assert.equal(isValidQmdIndex({}), false);
+ });
+});
+
+describe("qmdArgsWithIndex", () => {
+ test("prepends --index <name> when an index is provided", () => {
+ assert.deepEqual(qmdArgsWithIndex("obsidian-mind", ["update"]), [
+ "--index",
+ "obsidian-mind",
+ "update",
+ ]);
+ });
+ test("returns subcommand args unchanged when index is null", () => {
+ assert.deepEqual(qmdArgsWithIndex(null, ["update"]), ["update"]);
+ });
+ test("preserves multi-arg subcommand invocations", () => {
+ assert.deepEqual(
+ qmdArgsWithIndex("vault", ["query", "ShardMind", "--json"]),
+ ["--index", "vault", "query", "ShardMind", "--json"],
+ );
+ });
+ test("returns a fresh array (does not mutate the input)", () => {
+ const input = ["update"];
+ const out = qmdArgsWithIndex(null, input);
+ assert.notEqual(out, input);
+ assert.deepEqual(out, input);
+ });
+});
+
describe("formatBrainIndex", () => {
test("renders one wikilink + description per entry", () => {
const out = formatBrainIndex([
diff --git a/.claude/scripts/tsconfig.json b/.claude/scripts/tsconfig.json
index 8c1dec4..b8a9d41 100644
--- a/.claude/scripts/tsconfig.json
+++ b/.claude/scripts/tsconfig.json
@@ -15,6 +15,10 @@
"types": ["node"],
"resolveJsonModule": true
},
- "include": ["**/*.ts", "../../.github/scripts/**/*.ts"],
+ "include": [
+ "**/*.ts",
+ "../../.github/scripts/**/*.ts",
+ "../../scripts/**/*.ts"
+ ],
"exclude": ["node_modules"]
}
diff --git a/.claude/skills/qmd/SKILL.md b/.claude/skills/qmd/SKILL.md
index 8ba3f72..b8c5f94 100644
--- a/.claude/skills/qmd/SKILL.md
+++ b/.claude/skills/qmd/SKILL.md
@@ -7,30 +7,63 @@ description: "Search the vault using QMD semantic search. Use PROACTIVELY before
Before reading vault files directly, search with QMD first. It returns relevant snippets without burning context on full file reads.
+## 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.
+
+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.
+
+**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`:
+
+```bash
+INDEX=$(node -e '
+ 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);
+') || 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`.
+
## Commands
### Search (pick one per query)
-- `qmd query "..." --json -n 10` — Best quality. Hybrid BM25 + vector + LLM reranking. Use for complex or conceptual queries.
-- `qmd search "..." --json -n 10` — Fast BM25 keyword. Use for exact terms, names, ticket numbers, dates.
-- `qmd vsearch "..." --json -n 5` — Semantic only. Use for exploratory queries where you don't know the exact words.
+- `qmd --index <name> query "..." --json -n 10` — Best quality. Hybrid BM25 + vector + LLM reranking. Use for complex or conceptual queries.
+- `qmd --index <name> search "..." --json -n 10` — Fast BM25 keyword. Use for exact terms, names, ticket numbers, dates.
+- `qmd --index <name> vsearch "..." --json -n 5` — Semantic only. Use for exploratory queries where you don't know the exact words.
### Retrieve
-- `qmd get "path/to/file.md"` — Full document by path.
-- `qmd get "#docid"` — Full document by ID (from search results).
-- `qmd multi-get "org/people/*.md" --json -l 40` — Batch retrieve by glob pattern.
+- `qmd --index <name> get "path/to/file.md"` — Full document by path.
+- `qmd --index <name> get "#docid"` — Full document by ID (from search results).
+- `qmd --index <name> multi-get "org/people/*.md" --json -l 40` — Batch retrieve by glob pattern.
### Index Management
-- `qmd update` — Re-index after file changes (fast, ~1-2s incremental).
-- `qmd embed` — Regenerate vector embeddings (slower, run after bulk changes).
+- `qmd --index <name> update` — Re-index after file changes (fast, ~1-2s incremental). The SessionStart hook runs this automatically.
+- `qmd --index <name> embed` — Regenerate vector embeddings (slower, run after bulk changes).
+
+## Bootstrap (Fresh Clone)
+
+The QMD SQLite store lives outside the repo (`~/.cache/qmd/<index>.sqlite`), so a fresh clone starts with no index. Run the bootstrap once:
+
+```bash
+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.
## When to Search
-- User mentions a past decision, incident, person, project → `qmd query`
-- User asks "what did we decide about X" → `qmd query`
-- User mentions a person by name → `qmd search "<name>"`
-- Before creating a new note → `qmd vsearch "<topic>"` to check for existing content
-- After creating a note → `qmd vsearch "<note title>"` to find notes that should link to it
-- Loading context for review prep → `qmd multi-get "perf/evidence/*.md"`
-- Loading 1-on-1 context → `qmd search "<person name> 1-1"`
+- User mentions a past decision, incident, person, project → `qmd --index <name> query`
+- User asks "what did we decide about X" → `qmd --index <name> query`
+- User mentions a person by name → `qmd --index <name> search "<name>"`
+- Before creating a new note → `qmd --index <name> vsearch "<topic>"` to check for existing content
+- After creating a note → `qmd --index <name> vsearch "<note title>"` to find notes that should link to it
+- Loading context for review prep → `qmd --index <name> multi-get "perf/evidence/*.md"`
+- Loading 1-on-1 context → `qmd --index <name> search "<person name> 1-1"`
## After Bulk Changes
-Run `qmd update && qmd embed` to keep the index fresh. The SessionStart hook does `qmd update` automatically, but `qmd embed` should be run explicitly after sessions that create many notes.
+Run `qmd --index <name> update && qmd --index <name> embed` to keep the index fresh. The SessionStart hook does `qmd --index <name> update` automatically, but `qmd --index <name> embed` should be run explicitly after sessions that create many notes.
+
+## MCP Server
+
+`.mcp.json` wires QMD as an MCP server via `.claude/scripts/qmd-mcp.mjs` — a Node wrapper that bypasses the Windows npm shim and scopes the server to the same `qmd_index`. The `qmd` tools (`query`, `search`, `vsearch`, `get`, `multi-get`) appear in the Claude Code tool menu when QMD is installed. No per-query `--index` argument needed through the MCP — it's already scoped by the wrapper.
diff --git a/CLAUDE.md b/CLAUDE.md
index 1c8e3ec..acd4cca 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -11,7 +11,7 @@ This vault has [obsidian-skills](https://github.com/kepano/obsidian-skills) inst
- **json-canvas**: Create `.canvas` files with nodes, edges, and visual layouts. See `references/EXAMPLES.md`.
- **obsidian-bases**: Create `.base` files with views, filters, and formulas. Bases core plugin is enabled. See `references/FUNCTIONS_REFERENCE.md`.
- **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 -- `qmd query "..."` for hybrid search, `qmd search "..."` for keyword, `qmd vsearch "..."` for semantic. Also registered as an MCP server via `.mcp.json` (project root), so the `qmd` tools are available directly in the Claude Code tool menu when QMD is installed. Falls back to grep/glob if QMD not installed.
+- **qmd**: Semantic search across the vault via [QMD](https://github.com/tobi/qmd). Use PROACTIVELY before reading files -- `qmd --index <name> query "..."` for hybrid search, `qmd --index <name> search "..."` for keyword, `qmd --index <name> vsearch "..."` for semantic. **Always pass `--index <name>`** where `<name>` is the `qmd_index` field from `vault-manifest.json` -- this keeps the SQLite store isolated from any other vault that shares the machine. Also registered as an MCP server via `.mcp.json` using `.claude/scripts/qmd-mcp.mjs`, which reads the same manifest field so the CLI, MCP, and SessionStart hook all scope to the same store. On a fresh clone, run `node --experimental-strip-types scripts/qmd-bootstrap.ts` once to build the index. Falls back to grep/glob if QMD not installed.
### Custom Slash Commands
diff --git a/README.ja.md b/README.ja.md
index f1f9fdc..85bc6f4 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -109,9 +109,15 @@ Decision: defer Redis migration. Win: Sarah praised the auth architecture.
```bash
npm install -g @tobilu/qmd
-qmd collection add . --name vault --mask "**/*.md"
-qmd context add qmd://vault "Engineer's work vault: projects, decisions, incidents, people, reviews, architecture"
-qmd update && qmd embed
+node --experimental-strip-types scripts/qmd-bootstrap.ts
+```
+
+ブートストラップは冪等で、再実行しても安全です。`vault-manifest.json` の `qmd_index` と `qmd_context` フィールドを読み取り、名前付きインデックスを登録してエンベディングを生成します(デフォルトのインデックス名は `obsidian-mind`)。SessionStart フック、`.mcp.json` のラッパー、CLI コマンドはすべて同じマニフェストフィールドを参照するため、同一マシン上の他のボールトと QMD データが混ざりません。CLI 実行時は常に `--index <名前>` を渡してください:
+
+```bash
+qmd --index obsidian-mind query "キャッシュについて何を決めた?"
+qmd --index obsidian-mind update # 一括編集後
+qmd --index obsidian-mind embed # 多数の新規ノート後
```
> [!NOTE]
diff --git a/README.ko.md b/README.ko.md
index 7c6fc8a..6d60c2c 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -109,9 +109,15 @@ You: "wrap up"
```bash
npm install -g @tobilu/qmd
-qmd collection add . --name vault --mask "**/*.md"
-qmd context add qmd://vault "Engineer's work vault: projects, decisions, incidents, people, reviews, architecture"
-qmd update && qmd embed
+node --experimental-strip-types scripts/qmd-bootstrap.ts
+```
+
+부트스트랩은 멱등성이 있어 재실행해도 안전합니다. `vault-manifest.json` 의 `qmd_index` 와 `qmd_context` 필드를 읽어 명명된 인덱스를 등록하고 임베딩을 생성합니다 (기본 인덱스 이름: `obsidian-mind`). SessionStart 훅, `.mcp.json` 래퍼, CLI 명령은 모두 동일한 매니페스트 필드를 참조하므로, 같은 머신의 다른 볼트와 QMD 데이터가 섞이지 않습니다. CLI 명령에는 항상 `--index <이름>` 을 전달하세요:
+
+```bash
+qmd --index obsidian-mind query "캐싱에 대해 뭘 결정했지?"
+qmd --index obsidian-mind update # 일괄 편집 후
+qmd --index obsidian-mind embed # 많은 신규 노트 후
```
> [!NOTE]
diff --git a/README.md b/README.md
index d35a4db..9b2a655 100644
--- a/README.md
+++ b/README.md
@@ -113,9 +113,17 @@ QMD is where most of the agent's retrieval intelligence comes from. Optional in
```bash
npm install -g @tobilu/qmd
-qmd collection add . --name vault --mask "**/*.md"
-qmd context add qmd://vault "Engineer's work vault: projects, decisions, incidents, people, reviews, architecture"
-qmd update && qmd embed
+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.
+
+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:
+
+```bash
+qmd --index obsidian-mind query "what did we decide about caching"
+qmd --index obsidian-mind update # after bulk edits
+qmd --index obsidian-mind embed # after many new notes
```
> [!NOTE]
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 1c60e6c..1ccda55 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -109,9 +109,15 @@ Decision: defer Redis migration. Win: Sarah praised the auth architecture.
```bash
npm install -g @tobilu/qmd
-qmd collection add . --name vault --mask "**/*.md"
-qmd context add qmd://vault "Engineer's work vault: projects, decisions, incidents, people, reviews, architecture"
-qmd update && qmd embed
+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 <名称>`:
+
+```bash
+qmd --index obsidian-mind query "我们关于缓存做了什么决策"
+qmd --index obsidian-mind update # 批量编辑后
+qmd --index obsidian-mind embed # 大量新笔记后
```
> [!NOTE]
diff --git a/brain/Skills.md b/brain/Skills.md
index 1b79ba7..bddd742 100644
--- a/brain/Skills.md
+++ b/brain/Skills.md
@@ -108,14 +108,14 @@ 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:
+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`):
-- `qmd query "..."` — hybrid BM25 + vector + LLM reranking (best quality)
-- `qmd search "..."` — fast BM25 keyword search
-- `qmd vsearch "..."` — semantic vector search (exploratory)
-- `qmd update && qmd embed` — refresh index after bulk changes
+- `qmd --index <name> query "..."` — hybrid BM25 + vector + LLM reranking (best quality)
+- `qmd --index <name> search "..."` — fast BM25 keyword search
+- `qmd --index <name> vsearch "..."` — semantic vector search (exploratory)
+- `qmd --index <name> update && qmd --index <name> embed` — refresh index after bulk changes
-SessionStart hook runs `qmd update` automatically. See `.claude/skills/qmd/SKILL.md` for full reference.
+SessionStart hook runs `qmd --index <name> update` automatically, reading the index name from the manifest. First-time setup on a fresh clone: `node --experimental-strip-types scripts/qmd-bootstrap.ts`. See `.claude/skills/qmd/SKILL.md` for full reference, and [[Memories]] for the topics QMD is most often asked to find across the vault.
## Workflow: Weekly Review
diff --git a/scripts/package.json b/scripts/package.json
new file mode 100644
index 0000000..4de7143
--- /dev/null
+++ b/scripts/package.json
@@ -0,0 +1,5 @@
+{
+ "private": true,
+ "type": "module",
+ "description": "Top-level user-facing scripts (qmd-bootstrap, etc.). ESM-only, executed via `node --experimental-strip-types`. The `type: module` field exists so TypeScript's verbatimModuleSyntax treats these .ts files as ESM during typecheck, matching their runtime behavior."
+}
diff --git a/scripts/qmd-bootstrap.ts b/scripts/qmd-bootstrap.ts
new file mode 100644
index 0000000..3e7cbdb
--- /dev/null
+++ b/scripts/qmd-bootstrap.ts
@@ -0,0 +1,228 @@
+#!/usr/bin/env node
+/**
+ * qmd-bootstrap.ts — idempotent QMD setup for this vault.
+ *
+ * Run once on a fresh clone (new machine, wiped cache, rebuilt index) to:
+ *
+ * 1. Register this vault as a QMD collection under the named index declared
+ * in vault-manifest.json (`qmd_index`).
+ * 2. Attach the vault's context string (`qmd_context`) so QMD's snippets
+ * and rerank step know what this collection is.
+ * 3. Walk the vault and build the sparse index.
+ * 4. Generate vector embeddings.
+ *
+ * Safe to re-run. Every step reports current state rather than failing on
+ * "already exists" — the context string is re-attached so updates to
+ * vault-manifest.json propagate. The SQLite store itself lives in
+ * ~/.cache/qmd/<index>.sqlite (derived data, not version-controlled), which
+ * is why this script is the portable instruction set for regenerating it.
+ *
+ * Cross-platform: every spawn routes through `buildQmdCommand`, which resolves
+ * @tobilu/qmd's real JS entry and runs it with the current Node binary. No
+ * platform conditionals — the same command path executes on Windows, macOS,
+ * and Linux.
+ *
+ * Usage:
+ * node --experimental-strip-types scripts/qmd-bootstrap.ts
+ */
+
+import { spawnSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+
+import { buildQmdCommand, resolveQmdEntry } from "../.claude/scripts/lib/qmd.ts";
+import { isValidQmdIndex } from "../.claude/scripts/lib/session-start.ts";
+
+type ManifestSubset = {
+ readonly qmd_index?: string;
+ readonly qmd_context?: string;
+ readonly template?: string;
+};
+
+function readManifest(): ManifestSubset | 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;
+ }
+ } catch {
+ /* handled by caller */
+ }
+ return null;
+}
+
+type SpawnOutcome = {
+ readonly status: number | null;
+ readonly signal: NodeJS.Signals | null;
+ readonly stdout: string;
+ readonly stderr: string;
+};
+
+/**
+ * Run qmd and capture both streams so callers can classify failures.
+ * Captured output is echoed to the user afterward so the visible log matches
+ * `stdio: "inherit"` ordering.
+ */
+function spawnQmd(
+ entry: string | null,
+ subcommandArgs: readonly string[],
+): SpawnOutcome {
+ const { cmd, args, shell } = buildQmdCommand(entry, subcommandArgs);
+ const r = spawnSync(cmd, args as string[], { shell, encoding: "utf-8" });
+ return {
+ status: r.status,
+ signal: r.signal,
+ stdout: r.stdout ?? "",
+ stderr: r.stderr ?? "",
+ };
+}
+
+function echo(outcome: SpawnOutcome): void {
+ if (outcome.stdout) process.stdout.write(outcome.stdout);
+ if (outcome.stderr) process.stderr.write(outcome.stderr);
+}
+
+function ensureQmd(entry: string | null): void {
+ const probe = spawnQmd(entry, ["--version"]);
+ if (probe.status !== 0) {
+ process.stderr.write(
+ "qmd not found. Install it first: npm i -g @tobilu/qmd\n",
+ );
+ process.exit(1);
+ }
+}
+
+/**
+ * Run a qmd subcommand and treat any non-zero exit as fatal. Echoes captured
+ * stdout/stderr before exiting so the user sees qmd's own diagnostic.
+ */
+function run(
+ entry: string | null,
+ args: readonly string[],
+ description: string,
+): void {
+ process.stdout.write(`→ ${description}\n`);
+ const outcome = spawnQmd(entry, args);
+ echo(outcome);
+ if (outcome.status !== 0) {
+ process.stderr.write(
+ `qmd exited with code ${outcome.status ?? "?"} during: ${description}\n`,
+ );
+ process.exit(outcome.status ?? 1);
+ }
+}
+
+/**
+ * Run a qmd subcommand that is *expected* to fail idempotently (e.g. removing
+ * a context entry that may not exist). Callers pass a predicate that inspects
+ * the captured stderr/stdout and returns true when the failure matches the
+ * known-benign case; any other failure is surfaced as a prominent warning so
+ * it isn't silently masked.
+ *
+ * This replaces a plain "ignore all failures" helper that would swallow real
+ * problems (invalid pattern, permissions, qmd install drift) alongside the
+ * benign ones.
+ */
+function runIdempotent(
+ entry: string | null,
+ args: readonly string[],
+ description: string,
+ isBenignFailure: (outcome: SpawnOutcome) => boolean,
+): void {
+ process.stdout.write(`→ ${description}\n`);
+ const outcome = spawnQmd(entry, args);
+ echo(outcome);
+ if (outcome.status !== 0 && !isBenignFailure(outcome)) {
+ process.stderr.write(
+ `\n⚠ qmd exited with code ${outcome.status ?? "?"} during: ${description}\n` +
+ ` This wasn't the expected idempotent failure. Continuing, but review the output above.\n\n`,
+ );
+ }
+}
+
+function main(): void {
+ const manifest = readManifest();
+ if (!manifest) {
+ process.stderr.write(
+ "vault-manifest.json missing or unreadable. Run from the vault root.\n",
+ );
+ process.exit(1);
+ }
+
+ const index = manifest.qmd_index;
+ if (!index) {
+ process.stderr.write(
+ "vault-manifest.json has no `qmd_index` field. Add one before running the bootstrap.\n",
+ );
+ process.exit(1);
+ }
+ if (!isValidQmdIndex(index)) {
+ 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",
+ );
+ process.exit(1);
+ }
+
+ // Resolve once up front so every downstream spawn reuses the same entry.
+ const entry = resolveQmdEntry();
+
+ ensureQmd(entry);
+
+ const collectionName = manifest.template ?? index;
+ const contextPath = `qmd://${collectionName}/`;
+ const contextText =
+ manifest.qmd_context ??
+ "Obsidian vault template with persistent AI agent memory.";
+
+ process.stdout.write(`→ Bootstrapping QMD index '${index}'\n`);
+
+ // `collection add` fails with a specific message when the collection is
+ // already registered — that's the idempotent case we expect on re-run.
+ // Any other failure (invalid pattern, permissions, qmd install drift) is
+ // surfaced as a warning so it isn't silently masked.
+ runIdempotent(
+ entry,
+ [
+ "--index",
+ index,
+ "collection",
+ "add",
+ ".",
+ collectionName,
+ "--pattern",
+ "**/*.md",
+ ],
+ `Registering collection '${collectionName}' (pattern **/*.md)`,
+ (o) => /already exists/i.test(o.stderr) || /already exists/i.test(o.stdout),
+ );
+
+ // Re-attach the context string so edits to vault-manifest.json propagate.
+ // On first run, `context rm` fails because the row doesn't exist — that's
+ // the expected benign case. Unexpected failures (auth, IO) get warned.
+ runIdempotent(
+ entry,
+ ["--index", index, "context", "rm", contextPath],
+ "Clearing previous context (if any)",
+ (o) =>
+ /not found/i.test(o.stderr) ||
+ /not found/i.test(o.stdout) ||
+ /does not exist/i.test(o.stderr) ||
+ /does not exist/i.test(o.stdout),
+ );
+ run(
+ entry,
+ ["--index", index, "context", "add", contextPath, contextText],
+ "Attaching vault context from manifest",
+ );
+
+ run(entry, ["--index", index, "update"], "Indexing vault files");
+ run(entry, ["--index", index, "embed"], "Generating embeddings");
+
+ process.stdout.write(
+ `\n✓ QMD index '${index}' ready. Test with:\n qmd --index ${index} query "<topic>"\n`,
+ );
+}
+
+main();
diff --git a/vault-manifest.json b/vault-manifest.json
index 7d0442e..81b868e 100644
--- a/vault-manifest.json
+++ b/vault-manifest.json
@@ -2,6 +2,8 @@
"template": "obsidian-mind",
"version": "5.0.0",
"released": "2026-04-17",
+ "qmd_index": "obsidian-mind",
+ "qmd_context": "Engineer's work vault built on obsidian-mind. Active projects and archive, 1:1 notes, incidents, brag log with quarterly evidence, competency map, people and teams, decisions and patterns in brain/, reference docs and runbooks. Multi-agent (Claude Code, Codex, Gemini) with lifecycle hooks and QMD semantic search. Ground for 'what did I ship?' reviews, project status, and personal knowledge management.",
"infrastructure": [
"CLAUDE.md",
"AGENTS.md",
@@ -20,6 +22,7 @@
".gemini/**",
"templates/**",
"bases/**",
+ "scripts/**",
"vault-manifest.json",
"obsidian-mind-logo.png",
"obsidian-mind-demo.gif",