Skip to content

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

fix: add a trailing flush so edits inside the QMD refresh debounce window get indexed (#293)

Brenno Ferrari1c26352ad4c0
diff --git a/.claude/scripts/lib/qmd-refresh.ts b/.claude/scripts/lib/qmd-refresh.ts
index ae6f671..9f0b3d2 100644
--- a/.claude/scripts/lib/qmd-refresh.ts
+++ b/.claude/scripts/lib/qmd-refresh.ts
@@ -15,7 +15,7 @@
*/
import { spawn } from "node:child_process";
-import { statSync, writeFileSync } from "node:fs";
+import { rmSync, statSync, writeFileSync } from "node:fs";
import { resolve as resolvePath } from "node:path";
import { buildQmdCommand, resolveQmdEntry } from "./qmd.ts";
import { debug } from "./hook-io.ts";
@@ -81,6 +81,106 @@ export function isDebounced(
return elapsed < debounceMs;
}
+/**
+ * How long a `.pending` marker is trusted past the end of the window it was
+ * written for. A marker older than that belongs to a trailing worker that
+ * never ran (killed, machine slept) and must not suppress flushes forever.
+ */
+export const PENDING_GRACE_MS = 60_000;
+
+/**
+ * How far in the future a marker's mtime may sit and still be trusted. The
+ * filesystem clock and `Date.now()` disagree by fractions of a millisecond,
+ * so a marker written moments ago can read as just ahead of now; beyond this
+ * it is a genuinely wrong clock and is not trusted.
+ */
+export const CLOCK_SKEW_MS = 2_000;
+
+export type RefreshPlan = "now" | "trailing" | "skip";
+
+/**
+ * Decide what one trigger does. The debounce bounds machine drag from a
+ * burst of writes, but on its own it only fires on the LEADING edge: a note
+ * written inside the window after a refresh was never indexed until some
+ * unrelated trigger landed outside it, and the last write of a session
+ * stayed unsearchable until the next SessionStart.
+ *
+ * - `now` — outside the window: refresh immediately.
+ * - `trailing` — inside the window, and no flush owed yet: schedule one for
+ * the window's end.
+ * - `skip` — inside the window, and a flush is already owed (a live
+ * pending marker): that flush will cover this write too.
+ */
+export function planRefresh(
+ sentinelMtimeMs: number | null,
+ pendingMtimeMs: number | null,
+ nowMs: number,
+ debounceMs: number,
+): RefreshPlan {
+ if (!isDebounced(sentinelMtimeMs, nowMs, debounceMs)) return "now";
+ const pendingLive =
+ pendingMtimeMs !== null &&
+ nowMs - pendingMtimeMs > -CLOCK_SKEW_MS &&
+ nowMs - pendingMtimeMs < debounceMs + PENDING_GRACE_MS;
+ return pendingLive ? "skip" : "trailing";
+}
+
+/** The marker that records a trailing flush is owed. */
+export function pendingPathFor(sentinelPath: string): string {
+ return `${sentinelPath}.pending`;
+}
+
+/**
+ * The trailing worker's gate, run once it has slept out the window. Clears
+ * the pending marker FIRST, so a write landing during this flush schedules
+ * the next one rather than being skipped. Then runs only if no refresh has
+ * started since the flush was scheduled (`scheduledAfterMs` is the sentinel
+ * mtime the scheduler saw): a newer refresh already covers these writes.
+ * When it runs, it stamps the sentinel like any other refresh.
+ */
+export function claimTrailingFlush(
+ sentinelPath: string,
+ scheduledAfterMs: number | null,
+): boolean {
+ try {
+ rmSync(pendingPathFor(sentinelPath), { force: true });
+ } catch {
+ /* a marker we cannot remove ages out via PENDING_GRACE_MS */
+ }
+ const current = readSentinelMtime(sentinelPath);
+ if (current !== null && scheduledAfterMs !== null && current > scheduledAfterMs) {
+ return false;
+ }
+ touchSentinel(sentinelPath);
+ return true;
+}
+
+/**
+ * Parse the worker's trailing-flush arguments. Absent or malformed → an
+ * immediate run, exactly as before trailing flushes existed. The delay is
+ * capped so a bad value cannot park a detached process for long.
+ */
+export function parseWorkerArgs(argv: readonly string[]): {
+ readonly trailing: { readonly delayMs: number; readonly sentinelPath: string; readonly afterMs: number | null } | null;
+} {
+ const get = (name: string): string | null => {
+ const hit = argv.find((a) => a.startsWith(`--${name}=`));
+ return hit === undefined ? null : hit.slice(name.length + 3);
+ };
+ const sentinelPath = get("trailing");
+ const delay = Number(get("delay-ms"));
+ if (!sentinelPath || !Number.isFinite(delay) || delay < 0) return { trailing: null };
+ const afterRaw = get("after");
+ const after = afterRaw === null || afterRaw === "" ? Number.NaN : Number(afterRaw);
+ return {
+ trailing: {
+ delayMs: Math.min(delay, 120_000),
+ sentinelPath,
+ afterMs: Number.isFinite(after) ? after : null,
+ },
+ };
+}
+
/**
* Return the absolute vault root derived from a hook script's own
* directory. Hook scripts live at `<vault>/.claude/scripts/`, so going
@@ -183,13 +283,18 @@ function touchSentinel(sentinelPath: string): void {
* naked `spawn` creates on Windows. Errors are logged under HOOK_DEBUG
* only — production is silent per the hook protocol.
*/
-function spawnDetachedWorker(workerPath: string, logPrefix: string): void {
+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,
@@ -221,16 +326,52 @@ export function triggerDebouncedRefresh(opts: {
readonly workerPath: string;
readonly debounceMs: number;
readonly logPrefix: string;
+ /** Test seams; production uses the real resolver and spawn. */
+ readonly qmdAvailable?: () => boolean;
+ readonly spawnWorker?: (workerPath: string, args: readonly string[]) => void;
}): void {
+ const now = Date.now();
const mtime = readSentinelMtime(opts.sentinelPath);
- if (isDebounced(mtime, Date.now(), opts.debounceMs)) {
- debug(`${opts.logPrefix}: debounced`);
+ const pendingPath = pendingPathFor(opts.sentinelPath);
+ const plan = planRefresh(mtime, readSentinelMtime(pendingPath), now, opts.debounceMs);
+ if (plan === "skip") {
+ debug(`${opts.logPrefix}: debounced; trailing flush already pending`);
return;
}
- if (resolveQmdEntry() === null) {
+ const available = opts.qmdAvailable ?? (() => resolveQmdEntry() !== null);
+ if (!available()) {
debug(`${opts.logPrefix}: qmd not resolvable; skipping`);
return;
}
- touchSentinel(opts.sentinelPath);
- spawnDetachedWorker(opts.workerPath, opts.logPrefix);
+ const spawnWorker =
+ opts.spawnWorker ??
+ ((path: string, args: readonly string[]) => spawnDetachedWorker(path, opts.logPrefix, args));
+
+ if (plan === "now") {
+ touchSentinel(opts.sentinelPath);
+ spawnWorker(opts.workerPath, []);
+ return;
+ }
+
+ // Trailing: owe exactly one flush for this window. `wx` makes the claim
+ // exclusive, so two hooks racing inside the window spawn one worker.
+ try {
+ writeFileSync(pendingPath, "", { flag: "wx" });
+ } catch {
+ // The marker exists. A live one means another hook won the race and
+ // its worker covers this write; a stale one is reclaimed.
+ if (planRefresh(mtime, readSentinelMtime(pendingPath), now, opts.debounceMs) === "skip") return;
+ try {
+ writeFileSync(pendingPath, "");
+ } catch {
+ return;
+ }
+ }
+ const remaining = Math.max(0, (mtime ?? now) + opts.debounceMs - now);
+ debug(`${opts.logPrefix}: debounced; trailing flush in ${remaining}ms`);
+ spawnWorker(opts.workerPath, [
+ `--trailing=${opts.sentinelPath}`,
+ `--delay-ms=${remaining}`,
+ `--after=${mtime ?? ""}`,
+ ]);
}
diff --git a/.claude/scripts/qmd-refresh-run.ts b/.claude/scripts/qmd-refresh-run.ts
index 98d4213..9032b23 100644
--- a/.claude/scripts/qmd-refresh-run.ts
+++ b/.claude/scripts/qmd-refresh-run.ts
@@ -38,7 +38,9 @@ import { debug } from "./lib/hook-io.ts";
import { resolveQmdIndex } from "./lib/session-start.ts";
import { resolveQmdEntry } from "./lib/qmd.ts";
import {
+ claimTrailingFlush,
composeWorkerInvocations,
+ parseWorkerArgs,
resolveVaultRoot,
} from "./lib/qmd-refresh.ts";
@@ -58,6 +60,18 @@ function readManifestRaw(): string | null {
// bootstrap script do. This worker WRITES to the store; if it resolved
// differently it would index one store while search reads another, and the
// symptom is stale results rather than an error.
+// Trailing flush: a trigger landed inside the debounce window, so this
+// worker sleeps out the rest of it, then runs unless a newer refresh has
+// already started (that refresh covers the same writes).
+const { trailing } = parseWorkerArgs(process.argv.slice(2));
+if (trailing !== null) {
+ await new Promise((r) => setTimeout(r, trailing.delayMs));
+ if (!claimTrailingFlush(trailing.sentinelPath, trailing.afterMs)) {
+ debug("qmd-refresh-run: trailing flush superseded by a newer refresh");
+ process.exit(0);
+ }
+}
+
const qmdIndex = resolveQmdIndex(readManifestRaw(), VAULT_ROOT);
const invocations = composeWorkerInvocations(qmdIndex, resolveQmdEntry());
diff --git a/.claude/scripts/tests/qmd-refresh.test.ts b/.claude/scripts/tests/qmd-refresh.test.ts
index c753331..72883bf 100644
--- a/.claude/scripts/tests/qmd-refresh.test.ts
+++ b/.claude/scripts/tests/qmd-refresh.test.ts
@@ -14,13 +14,161 @@
import { test, describe } from "node:test";
import assert from "node:assert/strict";
-import { resolve as resolvePath, sep as pathSep } from "node:path";
+import { existsSync, mkdtempSync, statSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve as resolvePath, sep as pathSep } from "node:path";
import {
+ CLOCK_SKEW_MS,
+ PENDING_GRACE_MS,
+ claimTrailingFlush,
composeWorkerInvocations,
isDebounced,
+ parseWorkerArgs,
+ pendingPathFor,
+ planRefresh,
resolveVaultRoot,
shouldRefreshForPath,
+ triggerDebouncedRefresh,
} from "../lib/qmd-refresh.ts";
+import { rmTemp } from "./_helpers.ts";
+
+/**
+ * The debounce used to fire on the leading edge only: a note written inside
+ * the window after a refresh stayed unindexed until an unrelated trigger
+ * landed outside it — for the last write of a session, until the next
+ * SessionStart.
+ */
+describe("planRefresh — trailing edge", () => {
+ const W = 30_000;
+ test("outside the window → now", () => {
+ assert.equal(planRefresh(null, null, 1_000_000, W), "now");
+ assert.equal(planRefresh(1_000_000 - W, null, 1_000_000, W), "now");
+ });
+ test("inside the window, nothing owed → trailing", () => {
+ assert.equal(planRefresh(1_000_000 - 10_000, null, 1_000_000, W), "trailing");
+ });
+ test("inside the window, a live flush owed → skip", () => {
+ assert.equal(planRefresh(1_000_000 - 10_000, 1_000_000 - 5_000, 1_000_000, W), "skip");
+ });
+ test("a stale pending marker does not suppress the flush", () => {
+ const now = 10_000_000;
+ assert.equal(planRefresh(now - 10_000, now - (W + PENDING_GRACE_MS) - 1, now, W), "trailing");
+ });
+ test("a marker a hair ahead of now (fs clock skew) is still live", () => {
+ assert.equal(planRefresh(1_000_000 - 10_000, 1_000_000 + 0.5, 1_000_000, W), "skip");
+ });
+ test("a marker well in the future (a wrong clock) is not trusted", () => {
+ assert.equal(planRefresh(1_000_000 - 10_000, 1_000_000 + CLOCK_SKEW_MS + 1, 1_000_000, W), "trailing");
+ });
+});
+
+describe("triggerDebouncedRefresh — schedules one trailing flush per window", () => {
+ function fixture() {
+ const dir = mkdtempSync(join(tmpdir(), "qmd-trailing-"));
+ const sentinel = join(dir, ".qmd-refresh-sentinel");
+ const spawned: (readonly string[])[] = [];
+ const fire = () =>
+ triggerDebouncedRefresh({
+ sentinelPath: sentinel,
+ workerPath: "worker.ts",
+ debounceMs: 30_000,
+ logPrefix: "test",
+ qmdAvailable: () => true,
+ spawnWorker: (_p, args) => spawned.push(args),
+ });
+ return { dir, sentinel, spawned, fire };
+ }
+
+ test("leading write runs now; a write inside the window schedules a trailing flush; a third is covered", () => {
+ const f = fixture();
+ try {
+ f.fire();
+ assert.deepEqual(f.spawned, [[]], "leading edge runs immediately");
+ // Age the leading refresh to 10 s ago: two calls in the same
+ // millisecond can see the sentinel's mtime a hair AHEAD of
+ // Date.now(), which isDebounced deliberately reads as "not
+ // debounced" (clock skew). Real hooks are separate processes.
+ const t = (Date.now() - 10_000) / 1000;
+ utimesSync(f.sentinel, t, t);
+ f.fire();
+ assert.equal(f.spawned.length, 2, "the in-window write must not be dropped");
+ const args = f.spawned[1] as readonly string[];
+ assert.ok(args.includes(`--trailing=${f.sentinel}`));
+ const delay = Number(args.find((a) => a.startsWith("--delay-ms="))?.slice(11));
+ assert.ok(delay > 0 && delay <= 30_000, `delay ${delay}`);
+ assert.ok(existsSync(pendingPathFor(f.sentinel)));
+ f.fire();
+ assert.equal(f.spawned.length, 2, "one trailing worker per window, not one per write");
+ } finally {
+ rmTemp(f.dir);
+ }
+ });
+
+ test("a stale pending marker is reclaimed", () => {
+ const f = fixture();
+ try {
+ f.fire();
+ const t = (Date.now() - 10_000) / 1000;
+ utimesSync(f.sentinel, t, t);
+ writeFileSync(pendingPathFor(f.sentinel), "");
+ const old = (Date.now() - 30_000 - PENDING_GRACE_MS - 5_000) / 1000;
+ utimesSync(pendingPathFor(f.sentinel), old, old);
+ f.fire();
+ assert.equal(f.spawned.length, 2);
+ } finally {
+ rmTemp(f.dir);
+ }
+ });
+});
+
+describe("claimTrailingFlush — the worker's gate after sleeping", () => {
+ test("runs when no newer refresh started, clears the marker, stamps the sentinel", () => {
+ const dir = mkdtempSync(join(tmpdir(), "qmd-claim-"));
+ try {
+ const s = join(dir, "s");
+ writeFileSync(s, "");
+ const t = (Date.now() - 40_000) / 1000;
+ utimesSync(s, t, t);
+ const after = statSync(s).mtimeMs;
+ writeFileSync(pendingPathFor(s), "");
+ assert.equal(claimTrailingFlush(s, after), true);
+ assert.equal(existsSync(pendingPathFor(s)), false);
+ assert.ok(statSync(s).mtimeMs > after);
+ } finally {
+ rmTemp(dir);
+ }
+ });
+
+ test("skips when a newer refresh already stamped the sentinel, still clearing the marker", () => {
+ const dir = mkdtempSync(join(tmpdir(), "qmd-claim-"));
+ try {
+ const s = join(dir, "s");
+ writeFileSync(s, "");
+ writeFileSync(pendingPathFor(s), "");
+ const after = statSync(s).mtimeMs - 10_000;
+ assert.equal(claimTrailingFlush(s, after), false);
+ assert.equal(existsSync(pendingPathFor(s)), false);
+ } finally {
+ rmTemp(dir);
+ }
+ });
+});
+
+describe("parseWorkerArgs", () => {
+ test("no trailing args → an immediate run", () => {
+ assert.deepEqual(parseWorkerArgs([]), { trailing: null });
+ });
+ test("trailing args parse, and the delay is capped", () => {
+ const p = parseWorkerArgs(["--trailing=/v/s", "--delay-ms=999999", "--after=123"]);
+ assert.deepEqual(p.trailing, { delayMs: 120_000, sentinelPath: "/v/s", afterMs: 123 });
+ });
+ test("an empty --after means no prior sentinel", () => {
+ assert.equal(parseWorkerArgs(["--trailing=/v/s", "--delay-ms=5", "--after="]).trailing?.afterMs, null);
+ });
+ test("a malformed delay falls back to an immediate run", () => {
+ assert.deepEqual(parseWorkerArgs(["--trailing=/v/s", "--delay-ms=abc"]), { trailing: null });
+ });
+});
describe("shouldRefreshForPath — accepts vault markdown", () => {
test("accepts a relative vault note", () => {
diff --git a/.gitignore b/.gitignore
index c109b08..ea4526b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -45,6 +45,7 @@ node_modules/
.claude/scripts/.checklist-state.json
.claude/scripts/.stop-handoff/
.claude/scripts/.qmd-refresh-sentinel
+.claude/scripts/.qmd-refresh-sentinel.pending
# MCP server audit log — every vault read, with the calling repo and the query
# text. Local forensics, never history: it churns on every session, and the