Skip to content

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

fix: run the qmd refresh worker and its qmd steps outside the vault (#405)

Brenno Ferrari88fd781cea29
diff --git a/.claude/scripts/lib/qmd-cwd.ts b/.claude/scripts/lib/qmd-cwd.ts
new file mode 100644
index 0000000..590e187
--- /dev/null
+++ b/.claude/scripts/lib/qmd-cwd.ts
@@ -0,0 +1,73 @@
+/**
+ * Where a qmd call about the vault runs, and what it is told, so the refresh
+ * can run from the OS temp folder without holding the vault open (#404). On
+ * Windows a process's cwd locks its folder, and a refresh lasts minutes, so a
+ * rename or delete of the vault failed with EBUSY.
+ *
+ * Each rule follows what @tobilu/qmd reads against its cwd, as read in its
+ * 2.5.3 dist by mindframe (cli/qmd.js's index selection, collections.js's
+ * findLocalConfigPath and getConfigDir, store.js's getDefaultDbPath) and not
+ * yet re-read here (TBC). Ported from mindframe#144's `qmd-cwd.ts`.
+ */
+
+import { existsSync, realpathSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+
+/**
+ * The project-local qmd config at or above `dir`, as qmd looks for it when no
+ * `--index` is given (`findLocalConfigPath`, from its cwd): `.qmd/index.yaml`,
+ * then `.qmd/index.yml`, walking up. Null when none.
+ */
+export function localQmdConfigAt(dir: string): string | null {
+ for (let at = resolve(dir); ; at = dirname(at)) {
+ for (const name of ["index.yaml", "index.yml"]) {
+ const file = join(at, ".qmd", name);
+ if (existsSync(file)) return file;
+ }
+ if (dirname(at) === at) return null;
+ }
+}
+
+/**
+ * The cwd for a qmd call about `vault`: the OS temp folder. With an index
+ * name, qmd reads nothing against its cwd but the variables `qmdPathsAgainst`
+ * pins. Without one, it uses the first project-local config above its cwd,
+ * which no flag can pass, so the vault stays the cwd whenever the temp folder
+ * would find a different one (the vault's own, or one in the user profile the
+ * temp folder sits in on Windows). Both are walked as qmd walks its
+ * `process.cwd()`: by the real path on POSIX, where the cwd is always
+ * resolved, and as given on Windows, where it keeps a junction or `subst`
+ * drive. A temp folder that doesn't exist keeps the vault.
+ */
+export function qmdCwdFor(vault: string, qmdIndex: string | null, temp: string = tmpdir(), platform: NodeJS.Platform = process.platform): string {
+ if (!existsSync(temp)) return vault;
+ if (qmdIndex !== null) return temp;
+ const asCwd = (dir: string): string => (platform === "win32" ? dir : realOr(dir));
+ return localQmdConfigAt(asCwd(temp)) === localQmdConfigAt(asCwd(vault)) ? temp : vault;
+}
+
+const realOr = (dir: string): string => {
+ try {
+ return realpathSync.native(dir);
+ } catch {
+ return dir;
+ }
+};
+
+/**
+ * `env` with the path variables qmd reads against its cwd resolved against
+ * the vault: INDEX_PATH, QMD_CONFIG_DIR, XDG_CONFIG_HOME and XDG_CACHE_HOME
+ * (`getDefaultDbPath` and `getConfigDir` use them as given). A qmd call from
+ * outside the vault then reads them as the vault would have; an absolute one
+ * is kept, and a Windows root-relative one (`\idx`) takes the vault's drive.
+ * Empty ones are qmd's unset and stay so.
+ */
+export function qmdPathsAgainst(vault: string, env: Readonly<Record<string, string | undefined>>): Record<string, string | undefined> {
+ const pinned: Record<string, string | undefined> = { ...env };
+ for (const key of ["INDEX_PATH", "QMD_CONFIG_DIR", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"]) {
+ const value = env[key];
+ if (value) pinned[key] = resolve(vault, value);
+ }
+ return pinned;
+}
diff --git a/.claude/scripts/lib/qmd-refresh.ts b/.claude/scripts/lib/qmd-refresh.ts
index 1ee3abf..6652bf8 100644
--- a/.claude/scripts/lib/qmd-refresh.ts
+++ b/.claude/scripts/lib/qmd-refresh.ts
@@ -14,10 +14,10 @@
* delegates platform-specific spawn shape to `lib/qmd.ts`.
*/
-import { spawn } from "node:child_process";
-import { rmSync, statSync, writeFileSync } from "node:fs";
+import { existsSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
import { join, resolve as resolvePath } from "node:path";
-import { buildQmdCommand, REFRESH_SWITCH, refreshDisabled, resolveQmdEntry } from "./qmd.ts";
+import { buildQmdCommand, REFRESH_SWITCH, refreshDisabled, resolveQmdEntry, spawnDetachedQmd } from "./qmd.ts";
import { envPath } from "./env-path.ts";
import { debug } from "./hook-io.ts";
import { isInsideVault } from "./project-dir.ts";
@@ -40,9 +40,11 @@ const SKIP_SEGMENTS: readonly string[] = [
* Where the debounce sentinel lives: QMD_REFRESH_SENTINEL when set (tests point
* it at a temp file so parallel workers don't race on the shared one), else
* beside the hook scripts. Empty counts as unset (lib/env-path.ts, #360).
+ * Absolute, against this hook's cwd: the worker it is handed to runs from
+ * another (#404).
*/
export function sentinelPathFrom(env: Readonly<Record<string, string | undefined>>, scriptDir: string): string {
- return envPath(env, "QMD_REFRESH_SENTINEL", join(scriptDir, ".qmd-refresh-sentinel"));
+ return resolvePath(envPath(env, "QMD_REFRESH_SENTINEL", join(scriptDir, ".qmd-refresh-sentinel")));
}
/**
@@ -304,36 +306,21 @@ function touchSentinel(sentinelPath: string): void {
export { REFRESH_SWITCH, refreshDisabled } from "./qmd.ts";
/**
- * Spawn the detached worker. `stdio: 'ignore'` + `.unref()` + `detached`
- * survive parent exit without leaving file descriptors open, and
- * `windowsHide: true` suppresses the transient console window that a
- * naked `spawn` creates on Windows. Errors are logged under HOOK_DEBUG
- * only — production is silent per the hook protocol.
+ * The detached worker's cwd: the OS temp folder, so a worker that lasts
+ * minutes never holds the vault open (lib/qmd-cwd.ts, #404), or the hook's
+ * own when there is none. The worker finds the vault from its own path.
*/
-function spawnDetachedWorker(
- workerPath: string,
- logPrefix: string,
- workerArgs: readonly string[] = [],
-): void {
- const child = spawn(
- process.execPath,
- [
- "--disable-warning=ExperimentalWarning",
- "--experimental-strip-types",
- workerPath,
- ...workerArgs,
- ],
- {
- detached: true,
- stdio: "ignore",
- windowsHide: true,
- cwd: process.cwd(),
- },
- );
- child.on("error", (err) => {
- debug(`${logPrefix}: worker spawn error: ${err.message}`);
- });
- child.unref();
+export function workerCwd(temp: string = tmpdir()): string {
+ return existsSync(temp) ? temp : process.cwd();
+}
+
+/**
+ * Spawn the detached worker through the one detached spawner
+ * (`spawnDetachedQmd`, lib/qmd.ts). Exported for its spawning test.
+ */
+export function spawnDetachedWorker(workerPath: string, logPrefix: string, workerArgs: readonly string[] = []): void {
+ const args = ["--disable-warning=ExperimentalWarning", "--experimental-strip-types", workerPath, ...workerArgs];
+ spawnDetachedQmd({ cmd: process.execPath, args, shell: false }, logPrefix, workerCwd());
}
/**
diff --git a/.claude/scripts/lib/qmd.ts b/.claude/scripts/lib/qmd.ts
index af64c27..7002ea8 100644
--- a/.claude/scripts/lib/qmd.ts
+++ b/.claude/scripts/lib/qmd.ts
@@ -331,6 +331,7 @@ export function spawnDetachedQmd(
command: { readonly cmd: string; readonly args: readonly string[]; readonly shell: boolean },
label: string,
cwd?: string,
+ env?: NodeJS.ProcessEnv,
): boolean {
if (refreshDisabled()) {
debug(`${label}: qmd refresh off (${REFRESH_SWITCH}=off); nothing spawned`);
@@ -342,6 +343,7 @@ export function spawnDetachedQmd(
detached: true,
windowsHide: true,
...(cwd !== undefined ? { cwd } : {}),
+ ...(env !== undefined ? { env } : {}),
});
child.on("error", (err) => debug(`${label}: detached qmd failed to start: ${err.message}`));
child.unref();
diff --git a/.claude/scripts/qmd-refresh-run.ts b/.claude/scripts/qmd-refresh-run.ts
index 9032b23..d0d85bc 100644
--- a/.claude/scripts/qmd-refresh-run.ts
+++ b/.claude/scripts/qmd-refresh-run.ts
@@ -23,7 +23,8 @@
* hook fires from a drifted shell cwd without CLAUDE_PROJECT_DIR set —
* without that anchor, the manifest read failed silently and the
* worker updated QMD's default global collection instead of the
- * vault's named one.
+ * vault's named one. Its qmd steps run outside the vault
+ * (lib/qmd-cwd.ts, #404).
*
* Multi-platform: delegates the spawn shape to `lib/qmd.ts`, which
* routes through `process.execPath qmd.js` on every OS, bypassing the
@@ -37,6 +38,7 @@ import { fileURLToPath } from "node:url";
import { debug } from "./lib/hook-io.ts";
import { resolveQmdIndex } from "./lib/session-start.ts";
import { resolveQmdEntry } from "./lib/qmd.ts";
+import { qmdCwdFor, qmdPathsAgainst } from "./lib/qmd-cwd.ts";
import {
claimTrailingFlush,
composeWorkerInvocations,
@@ -74,6 +76,9 @@ if (trailing !== null) {
const qmdIndex = resolveQmdIndex(readManifestRaw(), VAULT_ROOT);
const invocations = composeWorkerInvocations(qmdIndex, resolveQmdEntry());
+// lib/qmd-cwd.ts (#404).
+const cwd = qmdCwdFor(VAULT_ROOT, qmdIndex);
+const env = qmdPathsAgainst(VAULT_ROOT, process.env);
for (const inv of invocations) {
const result = spawnSync(inv.cmd, inv.args as string[], {
@@ -81,7 +86,8 @@ for (const inv of invocations) {
timeout: inv.timeoutMs,
shell: inv.shell,
windowsHide: true,
- cwd: VAULT_ROOT,
+ cwd,
+ env,
});
if (result.error) {
debug(`qmd-refresh-run: ${inv.args.join(" ")} — ${result.error.message}`);
diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.ts
index 3aa6b0d..08eb1f8 100644
--- a/.claude/scripts/session-start.ts
+++ b/.claude/scripts/session-start.ts
@@ -26,7 +26,7 @@ import {
type Dirent,
} from "node:fs";
import { spawnSync } from "node:child_process";
-import { homedir, tmpdir } from "node:os";
+import { homedir } from "node:os";
import { join } from "node:path";
import {
take,
@@ -79,6 +79,7 @@ import {
resolveQmdEntry,
spawnDetachedQmd,
} from "./lib/qmd.ts";
+import { qmdCwdFor, qmdPathsAgainst } from "./lib/qmd-cwd.ts";
import {
formatActiveHygiene,
parseMemoryRoot,
@@ -284,18 +285,17 @@ const qmdUpdate = bootstrapNeeded
}
: 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();
+// cwd. The update runs where the refresh worker's qmd steps run, by the same
+// rule (lib/qmd-cwd.ts, #404): the OS temp folder, so the detached child
+// never holds the vault open on Windows, unless qmd would find a different
+// local config there, with its cwd-relative paths read against the vault.
+const qmdCwd = bootstrapNeeded ? cwd : qmdCwdFor(cwd, qmdIndex);
+const qmdEnv = bootstrapNeeded ? undefined : qmdPathsAgainst(cwd, process.env);
// VAULT_QMD_REFRESH=off (every test process carries it) stops this detached
// 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 (!reinjectBuild) spawnDetachedQmd(qmdUpdate, "session-start", qmdCwd);
+if (!reinjectBuild) spawnDetachedQmd(qmdUpdate, "session-start", qmdCwd, qmdEnv);
type CmdResult =
| { readonly kind: "ok"; readonly stdout: string }
diff --git a/.claude/scripts/tests/qmd-cwd.test.ts b/.claude/scripts/tests/qmd-cwd.test.ts
new file mode 100644
index 0000000..902a4d6
--- /dev/null
+++ b/.claude/scripts/tests/qmd-cwd.test.ts
@@ -0,0 +1,123 @@
+/**
+ * The qmd refresh never holds the vault open (lib/qmd-cwd.ts, #404).
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { localQmdConfigAt, qmdCwdFor, qmdPathsAgainst } from "../lib/qmd-cwd.ts";
+import { workerCwd } from "../lib/qmd-refresh.ts";
+import { rmTemp } from "./_helpers.ts";
+
+const SCRIPTS = join(dirname(fileURLToPath(import.meta.url)), "..");
+
+/** A temp root holding an empty `vault` and `temp` folder. */
+const withVaultAndTemp = (run: (vault: string, temp: string, root: string) => void): void => {
+ const root = mkdtempSync(join(tmpdir(), "qmd-cwd-"));
+ try {
+ mkdirSync(join(root, "vault"));
+ mkdirSync(join(root, "temp"));
+ run(join(root, "vault"), join(root, "temp"), root);
+ } finally {
+ rmTemp(root);
+ }
+};
+
+describe("qmdCwdFor", () => {
+ test("with an index name, the temp folder: qmd reads nothing else against its cwd", () => {
+ withVaultAndTemp((vault, temp) => assert.equal(qmdCwdFor(vault, "my-vault", temp), temp));
+ });
+
+ test("a temp folder that doesn't exist keeps the vault", () => {
+ withVaultAndTemp((vault, _temp, root) => assert.equal(qmdCwdFor(vault, "my-vault", join(root, "missing")), vault));
+ });
+
+ test("without an index, the vault whenever the temp folder would find a different local config", () => {
+ withVaultAndTemp((vault, temp) => {
+ mkdirSync(join(vault, ".qmd"));
+ writeFileSync(join(vault, ".qmd", "index.yml"), "");
+ assert.equal(qmdCwdFor(vault, null, temp), vault, "the vault's own config");
+ assert.equal(qmdCwdFor(vault, null, temp, "win32"), vault, "walked as given on Windows too");
+ });
+ });
+
+ test("without an index, the temp folder when both find the same config, or none", () => {
+ withVaultAndTemp((vault, temp) => {
+ assert.equal(qmdCwdFor(vault, null, temp), temp);
+ assert.equal(qmdCwdFor(vault, null, temp, "win32"), temp);
+ });
+ });
+});
+
+describe("localQmdConfigAt", () => {
+ test("walks up for .qmd/index.yaml, then .qmd/index.yml", () => {
+ withVaultAndTemp((vault, _temp, root) => {
+ const deep = join(vault, "a", "b");
+ mkdirSync(deep, { recursive: true });
+ mkdirSync(join(root, ".qmd"));
+ writeFileSync(join(root, ".qmd", "index.yml"), "");
+ assert.equal(localQmdConfigAt(deep), join(root, ".qmd", "index.yml"));
+ writeFileSync(join(root, ".qmd", "index.yaml"), "");
+ assert.equal(localQmdConfigAt(deep), join(root, ".qmd", "index.yaml"));
+ });
+ });
+});
+
+describe("qmdPathsAgainst", () => {
+ test("the paths qmd reads against its cwd are resolved against the vault; absolute and empty ones are kept", () => {
+ const vault = resolve(tmpdir(), "vault");
+ const absolute = resolve(tmpdir(), "abs-index.sqlite");
+ const env = qmdPathsAgainst(vault, {
+ INDEX_PATH: "data/index.sqlite",
+ QMD_CONFIG_DIR: "cfg",
+ XDG_CONFIG_HOME: absolute,
+ XDG_CACHE_HOME: "",
+ OTHER: "rel/path",
+ });
+ assert.equal(env["INDEX_PATH"], join(vault, "data", "index.sqlite"));
+ assert.equal(env["QMD_CONFIG_DIR"], join(vault, "cfg"));
+ assert.equal(env["XDG_CONFIG_HOME"], absolute);
+ assert.equal(env["XDG_CACHE_HOME"], "", "empty is qmd's unset");
+ assert.equal(env["OTHER"], "rel/path", "only qmd's path variables");
+ });
+});
+
+describe("workerCwd", () => {
+ test("the temp folder, or the hook's cwd when there is none", () => {
+ withVaultAndTemp((_vault, temp, root) => {
+ assert.equal(workerCwd(temp), temp);
+ assert.equal(workerCwd(join(root, "missing")), process.cwd());
+ });
+ });
+});
+
+/**
+ * The wiring, which the pure tests above can't reach: the worker's qmd steps
+ * and session start's detached update take their cwd and env from these
+ * helpers (a top-level script and a hook, so read as source).
+ */
+describe("each long qmd spawn takes its cwd and env from lib/qmd-cwd.ts", () => {
+ const source = (file: string) => readFileSync(join(SCRIPTS, file), "utf8");
+
+ test("the refresh worker's steps", () => {
+ const worker = source("qmd-refresh-run.ts");
+ assert.match(worker, /const cwd = qmdCwdFor\(VAULT_ROOT, qmdIndex\);/);
+ assert.match(worker, /const env = qmdPathsAgainst\(VAULT_ROOT, process\.env\);/);
+ assert.match(worker, /spawnSync\(inv\.cmd[\s\S]*?\bcwd,\s*env,\s*\}\);/);
+ });
+
+ test("the refresh worker itself", () => {
+ assert.match(source("lib/qmd-refresh.ts"), /spawnDetachedQmd\(\{ cmd: process\.execPath, args, shell: false \}, logPrefix, workerCwd\(\)\);/);
+ });
+
+ test("session start's detached update", () => {
+ const start = source("session-start.ts");
+ assert.match(start, /: qmdCwdFor\(cwd, qmdIndex\);/);
+ assert.match(start, /: qmdPathsAgainst\(cwd, process\.env\);/);
+ assert.match(start, /spawnDetachedQmd\(qmdUpdate, "session-start", qmdCwd, qmdEnv\)/);
+ });
+});
diff --git a/.claude/scripts/tests/qmd-refresh.integration.test.ts b/.claude/scripts/tests/qmd-refresh.integration.test.ts
index a4c94aa..e92f113 100644
--- a/.claude/scripts/tests/qmd-refresh.integration.test.ts
+++ b/.claude/scripts/tests/qmd-refresh.integration.test.ts
@@ -28,7 +28,10 @@ import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";
import { dirname, join, resolve } from "node:path";
import {
+ existsSync,
mkdtempSync,
+ readFileSync,
+ realpathSync,
rmSync,
statSync,
utimesSync,
@@ -37,6 +40,8 @@ import {
import { tmpdir } from "node:os";
import { runScript as spawnHook, rmTemp } from "./_helpers.ts";
import { resolveQmdEntry } from "../lib/qmd.ts";
+import { REFRESH_SWITCH } from "../lib/qmd.ts";
+import { spawnDetachedWorker } from "../lib/qmd-refresh.ts";
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
const SCRIPT = resolve(SCRIPT_DIR, "../validate-write.ts");
@@ -283,3 +288,33 @@ describe("validate-write refresh trigger — eligible .md path", () => {
}
});
});
+
+/**
+ * The detached worker runs from the OS temp folder (#404). A stub worker
+ * records its cwd; spawning it is why this lives with the integration tests.
+ */
+describe("qmd-refresh — the detached worker runs outside the vault (#404)", () => {
+ test("a worker spawned from inside a folder records the temp folder as its cwd", () => {
+ const root = mkdtempSync(join(tmpdir(), "refresh-worker-cwd-"));
+ const previous = process.cwd();
+ // The stub is not a qmd worker: let the one detached spawner start it.
+ const refresh = process.env[REFRESH_SWITCH];
+ delete process.env[REFRESH_SWITCH];
+ try {
+ const stub = join(root, "stub-worker.mjs");
+ const out = join(root, "cwd.txt");
+ writeFileSync(stub, 'import { writeFileSync } from "node:fs";\nwriteFileSync(process.argv[2], process.cwd());\n');
+ process.chdir(root); // the hook's cwd: the folder the worker must not hold
+ spawnDetachedWorker(stub, "test", [out]);
+ const tick = new Int32Array(new SharedArrayBuffer(4));
+ const deadline = Date.now() + 20_000;
+ while (!existsSync(out) && Date.now() < deadline) Atomics.wait(tick, 0, 0, 100);
+ assert.ok(existsSync(out), "the stub worker never wrote its cwd");
+ assert.equal(realpathSync.native(readFileSync(out, "utf8")), realpathSync.native(tmpdir()));
+ } finally {
+ if (refresh !== undefined) process.env[REFRESH_SWITCH] = refresh;
+ process.chdir(previous);
+ rmTemp(root);
+ }
+ });
+});
diff --git a/.claude/scripts/tests/sentinel-path.test.ts b/.claude/scripts/tests/sentinel-path.test.ts
index 40f7e04..7dcda32 100644
--- a/.claude/scripts/tests/sentinel-path.test.ts
+++ b/.claude/scripts/tests/sentinel-path.test.ts
@@ -10,7 +10,7 @@
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { readFileSync, readdirSync, statSync } from "node:fs";
-import { dirname, join, relative } from "node:path";
+import { dirname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { envPath } from "../lib/env-path.ts";
@@ -39,7 +39,11 @@ describe("envPath", () => {
describe("sentinelPathFrom", () => {
test("an empty QMD_REFRESH_SENTINEL is the default path beside the scripts", () => {
const dir = join("scripts", "dir");
- assert.equal(sentinelPathFrom({ QMD_REFRESH_SENTINEL: "" }, dir), join(dir, ".qmd-refresh-sentinel"));
+ assert.equal(sentinelPathFrom({ QMD_REFRESH_SENTINEL: "" }, dir), resolve(dir, ".qmd-refresh-sentinel"));
+ });
+
+ test("a relative QMD_REFRESH_SENTINEL is made absolute: the worker reads it from another cwd (#404)", () => {
+ assert.equal(sentinelPathFrom({ QMD_REFRESH_SENTINEL: "rel/sentinel" }, "scripts"), resolve("rel/sentinel"));
});
});