Skip to content

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

feat: QMD self-heal at SessionStart (empty store, ABI mismatch, version warn) (#122)

Brenno Ferraric6a2b9e21fe9
diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.ts
index 6ab67e0..f2665d7 100644
--- a/.claude/scripts/lib/session-start.ts
+++ b/.claude/scripts/lib/session-start.ts
@@ -4,6 +4,8 @@
* system, or invoking the Obsidian CLI.
*/
+import { join } from "node:path";
+
import { escapeRegex } from "./regex.ts";
export function take(stdout: string, n: number): string {
@@ -208,6 +210,69 @@ export function qmdArgsWithIndex(
: ["--index", index, ...subcommandArgs];
}
+/**
+ * True when a captured stderr blob is @tobilu/qmd's native `better-sqlite3`
+ * binding failing to load because it was compiled against a different Node
+ * ABI than the one currently running (`ERR_DLOPEN_FAILED` / a
+ * `NODE_MODULE_VERSION` mismatch message). This is a DISTINCT failure mode
+ * from "store missing/empty" (see `qmdStoreLooksEmpty` in the hook script):
+ * the sqlite file can be tens of MB and perfectly healthy, but every qmd
+ * invocation still crashes before it ever opens it, because the native
+ * addon itself won't load under the current Node binary — typically after
+ * a Node upgrade on the host machine. Query results and the whole MCP
+ * server go silently dark in this state (the fire-and-forget re-index spawn
+ * swallows the crash), so this check exists to catch it instead of letting
+ * a session quietly fall back to Grep/Read for the rest of its life.
+ */
+export function isQmdNativeAbiMismatch(stderr: string): boolean {
+ return (
+ stderr.includes("NODE_MODULE_VERSION") ||
+ stderr.includes("ERR_DLOPEN_FAILED")
+ );
+}
+
+/**
+ * Derive the @tobilu/qmd package root (the directory containing its
+ * package.json) from `resolveQmdEntry()`'s resolved entry path
+ * (`.../@tobilu/qmd/dist/cli/qmd.js`), so a native-module rebuild can run
+ * `npm rebuild` with that directory as its cwd — portable across a global
+ * npm install, a local one, Homebrew's node_modules layout, or Windows,
+ * without hardcoding any machine-specific prefix path. Returns null when
+ * the entry itself is null (no resolvable install to rebuild) or doesn't
+ * match the expected `dist/cli/qmd.js` shape.
+ */
+export function qmdPackageRootFromEntry(entry: string | null): string | null {
+ if (entry === null) return null;
+ const marker = join("dist", "cli", "qmd.js");
+ if (!entry.endsWith(marker)) return null;
+ const prefixLen = entry.length - marker.length - 1; // -1 drops the separator before "dist"
+ return prefixLen > 0 ? entry.slice(0, prefixLen) : null;
+}
+
+/**
+ * Extract the `qmd_min_version` string from a `vault-manifest.json` source.
+ * Returns null when the manifest is absent, malformed, or the field is not
+ * a string — the min-version check simply doesn't run then (the field is
+ * opt-in, and qmd itself is optional).
+ */
+export function parseQmdMinVersion(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_min_version" in parsed
+ ) {
+ const value = (parsed as Record<string, unknown>)["qmd_min_version"];
+ if (typeof value === "string" && value.length > 0) return value;
+ }
+ } catch {
+ /* malformed manifest → treat as missing */
+ }
+ return null;
+}
+
/**
* True if a directory-entry name has a `.md` extension. Compared case-
* insensitively so files saved as `.MD` or `.Md` (legal on case-insensitive
@@ -340,3 +405,19 @@ export function formatBrainIndex(
});
return lines.length > 0 ? lines.join("\n") : "(none)";
}
+
+/**
+ * Resolve the machine-local sqlite store path for a named qmd index,
+ * honoring XDG_CACHE_HOME exactly like @tobilu/qmd's own store.js (and the
+ * MCP wrapper's resolveIndexSqlitePath in qmd-mcp.mjs — kept in sync by
+ * behavior-locking tests on both, since .mjs exports can't be imported into
+ * .ts under strip-types). Pure: env and home are injected for testability.
+ */
+export function resolveIndexStorePath(
+ indexName: string,
+ env: Record<string, string | undefined>,
+ home: string,
+): string {
+ const base = env["XDG_CACHE_HOME"] ?? join(home, ".cache");
+ return join(base, "qmd", `${indexName}.sqlite`);
+}
diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.ts
index 8ba816e..c5f0e66 100644
--- a/.claude/scripts/session-start.ts
+++ b/.claude/scripts/session-start.ts
@@ -14,10 +14,11 @@ import {
readFileSync,
appendFileSync,
readdirSync,
+ statSync,
type Dirent,
} from "node:fs";
import { spawn, spawnSync } from "node:child_process";
-import { tmpdir } from "node:os";
+import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import {
take,
@@ -31,13 +32,21 @@ import {
stripFrontmatter,
hasBrainContent,
parseQmdIndex,
+ parseQmdMinVersion,
qmdArgsWithIndex,
+ isQmdNativeAbiMismatch,
+ qmdPackageRootFromEntry,
+ resolveIndexStorePath,
parseInfraRootFilenames,
isInfraFilename,
isMarkdownFilename,
collectOpenTasks,
} from "./lib/session-start.ts";
-import { buildQmdCommand, resolveQmdEntry } from "./lib/qmd.ts";
+import {
+ buildQmdCommand,
+ qmdVersionAtLeast,
+ resolveQmdEntry,
+} from "./lib/qmd.ts";
function readManifestRaw(): string | null {
try {
@@ -81,21 +90,111 @@ const infraRootFilenames = parseInfraRootFilenames(manifestJson);
// Route through `buildQmdCommand` so the shim-bypass logic that fixes
// the MCP wrapper applies here too.
const qmdIndex = parseQmdIndex(manifestJson);
-const qmdUpdate = buildQmdCommand(
- resolveQmdEntry(),
- qmdArgsWithIndex(qmdIndex, ["update"]),
-);
-// `cwd: tmpdir()` keeps the detached child from holding the vault dir as
-// its working directory. `qmd update --index <name>` reads collection
-// paths from YAML, so cwd is irrelevant to the work; pinning it to the OS
-// tmpdir means `rm -rf` of the vault (or a test cleanup) never races a
-// stale qmd handle on Windows.
+const qmdEntry = resolveQmdEntry();
+
+// qmd is OPTIONAL in this template: every self-heal path below is gated on
+// a resolvable install (`qmdEntry !== null`). A machine without qmd gets no
+// probes, no bootstrap spawn, no notes — the silent degradation it has today.
+
+// Self-heal a BROKEN qmd install, distinct from a missing one: if a Node
+// upgrade leaves @tobilu/qmd's native `better-sqlite3` binding compiled
+// against the wrong ABI, every invocation crashes before it opens the store
+// — the sqlite file can be tens of MB and perfectly healthy, and the
+// fire-and-forget re-index spawn swallows the crash, so semantic search
+// goes silently dark. Bounded to a status call (cheap, touches the store)
+// + a rebuild (the actual fix) — both timeboxed so a hung native build
+// can't blow the hook's timeout.
+let qmdSelfHealNote: string | null = null;
+if (qmdIndex !== null && qmdEntry !== null) {
+ const preflightCmd = buildQmdCommand(qmdEntry, [
+ "--index",
+ qmdIndex,
+ "status",
+ ]);
+ const preflight = spawnSync(preflightCmd.cmd, preflightCmd.args as string[], {
+ encoding: "utf-8",
+ timeout: 5_000,
+ shell: preflightCmd.shell,
+ });
+ if (isQmdNativeAbiMismatch(preflight.stderr ?? "")) {
+ const pkgRoot = qmdPackageRootFromEntry(qmdEntry);
+ if (pkgRoot !== null) {
+ const rebuild = spawnSync("npm rebuild better-sqlite3", {
+ cwd: pkgRoot,
+ encoding: "utf-8",
+ timeout: 20_000,
+ shell: true,
+ });
+ qmdSelfHealNote =
+ rebuild.status === 0
+ ? "⚠️ QMD's native module (better-sqlite3) was ABI-mismatched against this machine's Node version — auto-rebuilt this session. Semantic search may need one more `qmd update` to fully catch up; if the qmd MCP tools are still absent, a session restart picks them up."
+ : "⚠️ QMD's native module (better-sqlite3) is ABI-mismatched against this machine's Node version, and the automatic `npm rebuild better-sqlite3` did not complete cleanly — semantic search is likely dead. Manual fix: `npm rebuild better-sqlite3` inside the @tobilu/qmd package directory, then `qmd update`.";
+ }
+ }
+}
+
+// Min-version check (#100): warn-only here — a session must never be broken
+// by an old qmd, but a silently-old install shouldn't stay silent either.
+// Runs only when the manifest opts in via `qmd_min_version` AND qmd is
+// installed. The bootstrap enforces the same floor loudly.
+let qmdVersionNote: string | null = null;
+const qmdMinVersion = parseQmdMinVersion(manifestJson);
+if (qmdMinVersion !== null && qmdEntry !== null) {
+ const versionCmd = buildQmdCommand(qmdEntry, ["--version"]);
+ const v = spawnSync(versionCmd.cmd, versionCmd.args as string[], {
+ encoding: "utf-8",
+ timeout: 5_000,
+ shell: versionCmd.shell,
+ });
+ if (v.status === 0 && !qmdVersionAtLeast(v.stdout ?? "", qmdMinVersion)) {
+ qmdVersionNote = `⚠️ Installed qmd (${(v.stdout ?? "").trim()}) is below this vault's declared minimum (${qmdMinVersion}) — semantic search may misbehave. Update: \`npm i -g @tobilu/qmd\`, then re-run the bootstrap.`;
+ }
+}
+
+// Self-heal a machine that hasn't bootstrapped QMD yet: the store is
+// machine-local derived data (~/.cache/qmd/<index>.sqlite, never committed),
+// so a clean clone has no registered collection — and `qmd update` silently
+// no-ops forever in that state, leaving semantic search dead with no error
+// (an empty shell store can still exist at ~100KB; a populated one is tens
+// of MB). If the store is missing or implausibly small, run the idempotent
+// bootstrap (registers collection + context + index + embed) instead of
+// `update`. Threshold errs toward bootstrapping: it's safe to re-run by
+// design. Gated on an installed qmd — never bootstraps onto a machine that
+// hasn't opted into qmd at all.
+function qmdStoreLooksEmpty(index: string | null): boolean {
+ if (!index) return false; // no named index → keep legacy update behavior
+ try {
+ // XDG-aware, matching qmd's own store path — a hardcoded ~/.cache
+ // would force a full bootstrap every session for XDG_CACHE_HOME users.
+ const store = resolveIndexStorePath(index, process.env, homedir());
+ return statSync(store).size < 500_000;
+ } catch {
+ return true; // store missing / path differs → bootstrap (idempotent)
+ }
+}
+
+const bootstrapNeeded = qmdEntry !== null && qmdStoreLooksEmpty(qmdIndex);
+const qmdUpdate = bootstrapNeeded
+ ? {
+ cmd: process.execPath,
+ args: ["--experimental-strip-types", "scripts/qmd-bootstrap.ts"],
+ shell: false,
+ }
+ : buildQmdCommand(qmdEntry, qmdArgsWithIndex(qmdIndex, ["update"]));
+// Bootstrap resolves the script + vault-manifest.json relative to the vault
+// cwd; the update path pins cwd to tmpdir. `cwd: tmpdir()` keeps the
+// detached child from holding the vault dir as its working directory —
+// `qmd update --index <name>` reads collection paths from YAML, so cwd is
+// irrelevant to the work, and pinning it to the OS tmpdir means `rm -rf`
+// of the vault (or a test cleanup) never races a stale qmd handle on
+// Windows.
+const qmdCwd = bootstrapNeeded ? cwd : tmpdir();
const qmdChild = spawn(qmdUpdate.cmd, qmdUpdate.args as string[], {
stdio: "ignore",
shell: qmdUpdate.shell,
detached: true,
windowsHide: true,
- cwd: tmpdir(),
+ cwd: qmdCwd,
});
// Silence the spawn-error event so a missing qmd doesn't crash the hook;
// qmd is optional and the hook already degrades when it's not installed.
@@ -288,6 +387,13 @@ const sections = [
listMd().join("\n"),
];
+if (qmdSelfHealNote !== null) {
+ sections.push("", "### QMD Self-Heal", qmdSelfHealNote);
+}
+if (qmdVersionNote !== null) {
+ sections.push("", "### QMD Version", qmdVersionNote);
+}
+
const body = sections.join("\n") + "\n";
process.stdout.write(
body + "\n" + formatInjectionSize(Buffer.byteLength(body, "utf-8")) + "\n",
diff --git a/.claude/scripts/tests/session-start.test.ts b/.claude/scripts/tests/session-start.test.ts
index 3556468..3f115d7 100644
--- a/.claude/scripts/tests/session-start.test.ts
+++ b/.claude/scripts/tests/session-start.test.ts
@@ -7,6 +7,7 @@
import { test, describe } from "node:test";
import assert from "node:assert/strict";
+import { join } from "node:path";
import {
take,
formatDateHeader,
@@ -19,6 +20,10 @@ import {
stripFrontmatter,
hasBrainContent,
parseQmdIndex,
+ parseQmdMinVersion,
+ isQmdNativeAbiMismatch,
+ qmdPackageRootFromEntry,
+ resolveIndexStorePath,
qmdArgsWithIndex,
isValidQmdIndex,
parseInfraRootFilenames,
@@ -311,6 +316,60 @@ describe("qmdArgsWithIndex", () => {
});
});
+describe("isQmdNativeAbiMismatch", () => {
+ test("detects a NODE_MODULE_VERSION mismatch message", () => {
+ assert.equal(
+ isQmdNativeAbiMismatch(
+ "Error: The module '.../better_sqlite3.node'\nwas compiled against a different Node.js version using\nNODE_MODULE_VERSION 141. This version of Node.js requires\nNODE_MODULE_VERSION 147.",
+ ),
+ true,
+ );
+ });
+ test("detects the ERR_DLOPEN_FAILED error code alone", () => {
+ assert.equal(isQmdNativeAbiMismatch("code: 'ERR_DLOPEN_FAILED'"), true);
+ });
+ test("returns false for unrelated stderr", () => {
+ assert.equal(isQmdNativeAbiMismatch(""), false);
+ assert.equal(isQmdNativeAbiMismatch("command not found: qmd"), false);
+ });
+});
+
+describe("qmdPackageRootFromEntry", () => {
+ test("strips dist/cli/qmd.js to return the package root", () => {
+ const root = join("/opt/homebrew/lib/node_modules", "@tobilu", "qmd");
+ const entry = join(root, "dist", "cli", "qmd.js");
+ assert.equal(qmdPackageRootFromEntry(entry), root);
+ });
+ test("returns null for a null entry", () => {
+ assert.equal(qmdPackageRootFromEntry(null), null);
+ });
+ test("returns null when the entry doesn't match the expected shape", () => {
+ assert.equal(qmdPackageRootFromEntry("/some/other/path.js"), null);
+ });
+});
+
+describe("parseQmdMinVersion", () => {
+ test("extracts a declared min version", () => {
+ assert.equal(
+ parseQmdMinVersion(JSON.stringify({ qmd_min_version: "2.0.0" })),
+ "2.0.0",
+ );
+ });
+ test("null when absent, empty, non-string, or manifest malformed", () => {
+ assert.equal(parseQmdMinVersion(JSON.stringify({})), null);
+ assert.equal(
+ parseQmdMinVersion(JSON.stringify({ qmd_min_version: "" })),
+ null,
+ );
+ assert.equal(
+ parseQmdMinVersion(JSON.stringify({ qmd_min_version: 2 })),
+ null,
+ );
+ assert.equal(parseQmdMinVersion("not json"), null);
+ assert.equal(parseQmdMinVersion(null), null);
+ });
+});
+
describe("isMarkdownFilename", () => {
test("accepts lowercase .md", () => {
assert.equal(isMarkdownFilename("note.md"), true);
@@ -599,3 +658,18 @@ describe("formatInjectionSize", () => {
});
}
});
+
+describe("resolveIndexStorePath", () => {
+ test("uses XDG_CACHE_HOME when set (matches qmd's own store rule)", () => {
+ assert.equal(
+ resolveIndexStorePath("my-vault", { XDG_CACHE_HOME: "/xdg/cache" }, "/home/u"),
+ join("/xdg/cache", "qmd", "my-vault.sqlite"),
+ );
+ });
+ test("falls back to ~/.cache when XDG_CACHE_HOME is unset", () => {
+ assert.equal(
+ resolveIndexStorePath("my-vault", {}, "/home/u"),
+ join("/home/u", ".cache", "qmd", "my-vault.sqlite"),
+ );
+ });
+});