A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
fix: stop the MCP server's detached qmd embed under VAULT_QMD_REFRESH=off (#351)
Brenno Ferrari9bf60818559d
diff --git a/.claude/scripts/lib/mcp-server.ts b/.claude/scripts/lib/mcp-server.tsindex a34d304..1fdcf79 100644--- a/.claude/scripts/lib/mcp-server.ts+++ b/.claude/scripts/lib/mcp-server.ts@@ -13,7 +13,7 @@*/import { readFileSync, realpathSync } from "node:fs";-import { spawn, spawnSync } from "node:child_process";+import { spawnSync } from "node:child_process";import type { VaultContext } from "./mcp-context.ts";import { INSTRUCTIONS, PROMPTS } from "./mcp-context.ts";@@ -45,7 +45,7 @@ import { validateMemory, writeMemory, renderMemory, resolveLinks, neutralizeWikiimport { findSimilar } from "./memory-similarity.ts";import { markSuperseded, resolveSupersedes } from "./memory-supersede.ts";import { health } from "./memory-discover.ts";-import { resolveQmdEntry, buildQmdCommand } from "./qmd.ts";+import { resolveQmdEntry, buildQmdCommand, spawnDetachedQmd } from "./qmd.ts";import {resolveReasonConfig,reasonUsage,@@ -145,18 +145,26 @@ export function missingRequired(tool: string | undefined, args: Record<string, u* retrievable at all and is synchronous and bounded; `embed` only decides where* it ranks and is detached, because it runs a local model.*/-export function reindexSync(indexName: string | null): boolean {- const run = (sub: string): boolean => {- try {- const entry = resolveQmdEntry();- const args = indexName ? ["--index", indexName, sub] : [sub];- const { cmd, args: argv, shell } = buildQmdCommand(entry, args);- const r = spawnSync(cmd, [...argv], { shell, timeout: REINDEX_TIMEOUT_MS, stdio: "ignore" });- return r.status === 0;- } catch {- return false;- }- };+export function reindexSync(+ indexName: string | null,+ deps: { readonly run?: (sub: string) => boolean; readonly spawnEmbed?: (args: readonly string[]) => void } = {},+): boolean {+ const qmdArgs = (sub: string): string[] => (indexName ? ["--index", indexName, sub] : [sub]);+ const run =+ deps.run ??+ ((sub: string): boolean => {+ try {+ const { cmd, args: argv, shell } = buildQmdCommand(resolveQmdEntry(), qmdArgs(sub));+ const r = spawnSync(cmd, [...argv], { shell, timeout: REINDEX_TIMEOUT_MS, stdio: "ignore" });+ return r.status === 0;+ } catch {+ return false;+ }+ });+ // spawnDetachedQmd honours VAULT_QMD_REFRESH=off, which every test process+ // carries: the embed is skipped, the update above still runs (#347).+ const spawnEmbed =+ deps.spawnEmbed ?? ((args: readonly string[]) => void spawnDetachedQmd(buildQmdCommand(resolveQmdEntry(), args), "om-mcp"));// `update` indexes the text and is what makes the note retrievable at all, so// it is synchronous: reporting "recorded" before that is a lie the caller@@ -170,10 +178,7 @@ export function reindexSync(indexName: string | null): boolean {// of that group. Waiting on a local model run for ordering that corrects// itself moments later buys nothing: measured, it was most of the write.try {- const entry = resolveQmdEntry();- const args = indexName ? ["--index", indexName, "embed"] : ["embed"];- const { cmd, args: argv, shell } = buildQmdCommand(entry, args);- spawn(cmd, [...argv], { shell, detached: true, stdio: "ignore" }).unref();+ spawnEmbed(qmdArgs("embed"));} catch {/* ranking quality is best-effort; retrieval already works without it */}diff --git a/.claude/scripts/lib/qmd-refresh.ts b/.claude/scripts/lib/qmd-refresh.tsindex 4ea7e86..b518856 100644--- a/.claude/scripts/lib/qmd-refresh.ts+++ b/.claude/scripts/lib/qmd-refresh.ts@@ -17,7 +17,7 @@import { spawn } from "node:child_process";import { rmSync, statSync, writeFileSync } from "node:fs";import { resolve as resolvePath } from "node:path";-import { buildQmdCommand, resolveQmdEntry } from "./qmd.ts";+import { buildQmdCommand, REFRESH_SWITCH, refreshDisabled, resolveQmdEntry } from "./qmd.ts";import { debug } from "./hook-io.ts";import { qmdArgsWithIndex } from "./session-start.ts";@@ -276,22 +276,9 @@ function touchSentinel(sentinelPath: string): void {}}-/**- * The switch that stops the detached qmd refresh: this trigger's worker, and- * session-start's update. Every test process carries it, so a suite leaves- * no qmd work behind (#337); wiki-mind's vendored copy uses the same name- * (wiki-mind #93).- */-export const REFRESH_SWITCH = "VAULT_QMD_REFRESH";--/**- * Whether the detached qmd refresh is switched off for this process: exactly- * "off". wiki-mind's copy reads the same variable the same way, and one- * variable must mean the same to every vault's hooks.- */-export function refreshDisabled(): boolean {- return process.env[REFRESH_SWITCH] === "off";-}+// The switch lives in lib/qmd.ts beside the detached qmd spawn it guards+// (#347); re-exported here, where #338 defined it, so its importers hold.+export { REFRESH_SWITCH, refreshDisabled } from "./qmd.ts";/*** Spawn the detached worker. `stdio: 'ignore'` + `.unref()` + `detached`diff --git a/.claude/scripts/lib/qmd.ts b/.claude/scripts/lib/qmd.tsindex 34de5ca..d227b09 100644--- a/.claude/scripts/lib/qmd.ts+++ b/.claude/scripts/lib/qmd.ts@@ -20,10 +20,11 @@* a test failure on the CI matrix rather than a silent platform bug.*/-import { spawnSync } from "node:child_process";+import { spawn, spawnSync } from "node:child_process";import { existsSync } from "node:fs";import { createRequire } from "node:module";import { isAbsolute, join } from "node:path";+import { debug } from "./hook-io.ts";const require = createRequire(import.meta.url);@@ -153,6 +154,51 @@ export function buildQmdCommand(};}+/**+ * The switch that stops detached qmd work: the write-time refresh worker,+ * session-start's update, and the MCP server's embed. Every test process+ * carries it, so a suite leaves no qmd work behind (#337, #347); wiki-mind's+ * vendored copy uses the same name (wiki-mind #93).+ */+export const REFRESH_SWITCH = "VAULT_QMD_REFRESH";++/**+ * Whether detached qmd work is switched off for this process: exactly "off".+ * wiki-mind's copy reads the same variable the same way, and one variable+ * must mean the same to every vault's hooks.+ */+export function refreshDisabled(): boolean {+ return process.env[REFRESH_SWITCH] === "off";+}++/**+ * Spawn `command` detached, unless the switch is off: then log under `label`+ * and spawn nothing. The one place a detached qmd process starts, so no+ * caller can forget the switch. Its stdio is ignored, it gets no console+ * window on Windows, and a spawn error (qmd missing) is logged, never thrown+ * as an unhandled `error` event. Returns whether it spawned.+ */+export function spawnDetachedQmd(+ command: { readonly cmd: string; readonly args: readonly string[]; readonly shell: boolean },+ label: string,+ cwd?: string,+): boolean {+ if (refreshDisabled()) {+ debug(`${label}: qmd refresh off (${REFRESH_SWITCH}=off); nothing spawned`);+ return false;+ }+ const child = spawn(command.cmd, [...command.args], {+ stdio: "ignore",+ shell: command.shell,+ detached: true,+ windowsHide: true,+ ...(cwd !== undefined ? { cwd } : {}),+ });+ child.on("error", (err) => debug(`${label}: detached qmd failed to start: ${err.message}`));+ child.unref();+ return true;+}+/*** Parse a dotted version into a numeric triple. Accepts the bare "2.5.3"* shape and the `qmd --version` output shape ("qmd 2.5.3 (655769712a)") bydiff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.tsindex 7e00eb8..d9fa2e2 100644--- a/.claude/scripts/session-start.ts+++ b/.claude/scripts/session-start.ts@@ -25,7 +25,7 @@ import {statSync,type Dirent,} from "node:fs";-import { spawn, spawnSync } from "node:child_process";+import { spawnSync } from "node:child_process";import { homedir, tmpdir } from "node:os";import { join } from "node:path";import {@@ -77,6 +77,7 @@ import {buildQmdCommand,qmdVersionAtLeast,resolveQmdEntry,+ spawnDetachedQmd,} from "./lib/qmd.ts";import {formatActiveHygiene,@@ -86,7 +87,6 @@ import {} from "./lib/active-hygiene.ts";import { debug, envelopedLimit, fitWithMeter, type OutputLimit, readStdinJson, writeHookOutput } from "./lib/hook-io.ts";-import { REFRESH_SWITCH, refreshDisabled } from "./lib/qmd-refresh.ts";import { readOmMod } from "./lib/om-mod.ts";import { resolveProjectDir } from "./lib/project-dir.ts";@@ -279,21 +279,7 @@ const qmdCwd = bootstrapNeeded ? cwd : tmpdir();// update too, the same as the write-time refresh worker (#337): a test's// session-start would otherwise leave a qmd update or bootstrap running// against its temp vault after the run.-if (refreshDisabled()) {- debug(`session-start: qmd refresh off (${REFRESH_SWITCH}=off); nothing spawned`);-} else {- const qmdChild = spawn(qmdUpdate.cmd, qmdUpdate.args as string[], {- stdio: "ignore",- shell: qmdUpdate.shell,- detached: true,- windowsHide: true,- 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.- qmdChild.on("error", () => undefined);- qmdChild.unref();-}+spawnDetachedQmd(qmdUpdate, "session-start", qmdCwd);type CmdResult =| { readonly kind: "ok"; readonly stdout: string }diff --git a/.claude/scripts/tests/mcp-reindex.test.ts b/.claude/scripts/tests/mcp-reindex.test.tsnew file mode 100644index 0000000..367d411--- /dev/null+++ b/.claude/scripts/tests/mcp-reindex.test.ts@@ -0,0 +1,66 @@+/**+ * reindexSync after a write over MCP: the synchronous `update` that makes the+ * note retrievable, and the detached `embed` that only ranks it. Under+ * VAULT_QMD_REFRESH=off, which every test process carries, the embed is not+ * spawned: a suite leaves no qmd work behind (#337, #347).+ */++import { test, describe, afterEach } from "node:test";+import assert from "node:assert/strict";++import { reindexSync } from "../lib/mcp-server.ts";+import { REFRESH_SWITCH } from "../lib/qmd-refresh.ts";++/** Run `fn` with the switch and HOOK_DEBUG set as given, capturing stderr. */+function withEnv<T>(refreshSwitch: string | undefined, fn: () => T): { result: T; stderr: string } {+ const setEnv = (key: string, value: string | undefined) => {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ };+ const before = { sw: process.env[REFRESH_SWITCH], dbg: process.env["HOOK_DEBUG"] };+ setEnv(REFRESH_SWITCH, refreshSwitch);+ setEnv("HOOK_DEBUG", "1");+ let stderr = "";+ const write = process.stderr.write.bind(process.stderr);+ process.stderr.write = ((chunk: string | Uint8Array) => ((stderr += String(chunk)), true)) as typeof process.stderr.write;+ try {+ return { result: fn(), stderr };+ } finally {+ process.stderr.write = write;+ setEnv(REFRESH_SWITCH, before.sw);+ setEnv("HOOK_DEBUG", before.dbg);+ }+}++describe("reindexSync — the detached embed honours VAULT_QMD_REFRESH (#347)", () => {+ const ran: string[] = [];+ const run = (ok: boolean) => (sub: string) => (ran.push(sub), ok);+ afterEach(() => {+ ran.length = 0;+ });++ test("under VAULT_QMD_REFRESH=off, reindexSync indexes but spawns no embed", () => {+ const { result, stderr } = withEnv("off", () => reindexSync("om-test", { run: run(true) }));+ assert.equal(result, true, "the note is retrievable: update ran and succeeded");+ assert.deepEqual(ran, ["update"]);+ assert.match(stderr, /om-mcp: qmd refresh off \(VAULT_QMD_REFRESH=off\); nothing spawned/);+ });++ test("with the switch unset, a successful update spawns exactly one embed, with the index name", () => {+ const spawned: (readonly string[])[] = [];+ const { result } = withEnv(undefined, () =>+ reindexSync("om-test", { run: run(true), spawnEmbed: (args) => spawned.push(args) }),+ );+ assert.equal(result, true);+ assert.deepEqual(spawned, [["--index", "om-test", "embed"]]);+ });++ test("a failed update spawns no embed, and returns false", () => {+ const spawned: (readonly string[])[] = [];+ const { result } = withEnv(undefined, () =>+ reindexSync("om-test", { run: run(false), spawnEmbed: (args) => spawned.push(args) }),+ );+ assert.equal(result, false);+ assert.deepEqual(spawned, []);+ });+});