Skip to content

Self-hosted MCP server + dashboard giving Claude Code, Cursor & Hermes agents shared long-term memory over a git-backed markdown vault. Agent-native, Obsidian-compatible second brain — markdown RAG, no vector DB.

fix(git): one git child at a time, across every bundle copy (#11)

Ronalds Palacise97280621df9
diff --git a/lib/git-queue.test.ts b/lib/git-queue.test.ts
new file mode 100644
index 0000000..587c954
--- /dev/null
+++ b/lib/git-queue.test.ts
@@ -0,0 +1,214 @@
+import { describe, expect, test } from "bun:test";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { GitUnavailableError, SKIPPED, gitPausedFor, gitRead, invalidateGitReads, runGit, tryRunGit } from "./git-queue";
+
+// Standard ESM and a plain timer rather than `import.meta.dir` / `Bun.sleep`, for the reason
+// test/setup.ts gives: `next build` type-checks this file with tsc, which knows neither.
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * The crash this file guards against.
+ *
+ * Railway logged, on repeat: "Cannot rebase onto multiple branches.", then "cannot fork() for
+ * remote-https: Resource temporarily unavailable", then "getaddrinfo() thread failed to start",
+ * then SIGABRT and a restart. All three are one bug — concurrent git children on one clone —
+ * and the guard that was supposed to prevent it (`let gitBusy` in lib/git.ts) could not, because
+ * Next.js compiles that module into several server chunks and each copy got its own `let`.
+ */
+
+/** How long two tasks must overlap before we call the queue broken. Zero overlap is the contract. */
+const overlaps = (spans: Array<[number, number]>) =>
+ spans.some((a, i) => spans.some(([s, e], j) => j !== i && s < a[1] && e > a[0]));
+
+describe("one git child at a time", () => {
+ test("concurrent tasks never overlap, whatever order they were queued in", async () => {
+ const spans: Array<[number, number]> = [];
+ const task = async (ms: number) => {
+ const start = performance.now();
+ await sleep(ms);
+ spans.push([start, performance.now()]);
+ };
+
+ await Promise.all([runGit(() => task(20)), runGit(() => task(5)), runGit(() => task(15)), runGit(() => task(1))]);
+
+ expect(spans.length).toBe(4);
+ expect(overlaps(spans)).toBe(false);
+ });
+
+ test("a task that throws does not strand everything queued behind it", async () => {
+ const ran: string[] = [];
+ const boom = runGit(async () => {
+ ran.push("boom");
+ throw new Error("git exploded");
+ });
+ const after = runGit(async () => {
+ ran.push("after");
+ return "ok";
+ });
+
+ await expect(boom).rejects.toThrow("git exploded");
+ expect(await after).toBe("ok");
+ expect(ran).toEqual(["boom", "after"]);
+ });
+
+ test("a second writer skips instead of stacking onto the first", async () => {
+ let ran = 0;
+ const held = tryRunGit(() => sleep(20));
+ const skipped = await tryRunGit(async () => {
+ ran++;
+ });
+
+ expect(skipped).toBe(SKIPPED);
+ expect(ran).toBe(0);
+ await held;
+
+ // …and runs again once the queue drains, so a skipped tick is not a stuck one.
+ expect(await tryRunGit(async () => ++ran)).toBe(1);
+ });
+
+ test("a read in flight makes a writer wait its turn, not give up", async () => {
+ // The sidebar polls `git status` every 10s. That must never be the reason a human's "sync
+ // now" reports nothing to do — it only has to stop the two from spawning git at once.
+ const spans: Array<[number, number]> = [];
+ const task = async (ms: number) => {
+ const start = performance.now();
+ await sleep(ms);
+ spans.push([start, performance.now()]);
+ return "done";
+ };
+
+ const read = runGit(() => task(20));
+ const write = await tryRunGit(() => task(5));
+
+ expect(write).toBe("done");
+ expect(await read).toBe("done");
+ expect(overlaps(spans)).toBe(false);
+ });
+});
+
+describe("the queue is one queue, not one per bundle copy", () => {
+ /**
+ * The production defect, reproduced honestly.
+ *
+ * Turbopack emits this module into one chunk per entry group — the instrumentation entry that
+ * owns the pull loop gets its own, the API routes get theirs — so the process holds several
+ * module instances, and before the fix each held an independent lock. Copying the source to a
+ * second path and importing it gives a second instance the same way a second chunk does. Both
+ * copies must reach the same queue, or they run git simultaneously.
+ */
+ test("a second instance of this module serializes against the first", async () => {
+ const copy = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "engram-queue-")), "git-queue.ts");
+ fs.copyFileSync(path.join(HERE, "git-queue.ts"), copy);
+ const second = (await import(copy)) as typeof import("./git-queue");
+
+ // A different module instance, not the same object handed back by the loader.
+ expect(second.runGit).not.toBe(runGit);
+
+ const spans: Array<[number, number]> = [];
+ const task = async (ms: number) => {
+ const start = performance.now();
+ await sleep(ms);
+ spans.push([start, performance.now()]);
+ };
+
+ await Promise.all([runGit(() => task(20)), second.runGit(() => task(20))]);
+ expect(spans.length).toBe(2);
+ expect(overlaps(spans)).toBe(false);
+
+ // A writer in one copy makes a writer in the other skip — the guarantee the production bug
+ // broke. And the sentinel survives the boundary: a `Symbol()` per copy would not compare
+ // equal, which is what made every completed sync look like a skipped one.
+ const held = tryRunGit(() => sleep(20));
+ expect(await second.tryRunGit(async () => "should not run")).toBe(SKIPPED);
+ await held;
+
+ fs.rmSync(path.dirname(copy), { recursive: true, force: true });
+ });
+});
+
+describe("running out of processes stops git instead of retrying into a crash", () => {
+ const exhausted = () =>
+ runGit(async () => {
+ throw new Error("unable to access 'https://github.com/x/y/': getaddrinfo() thread failed to start");
+ });
+
+ test("three consecutive fork/thread failures pause git; a success clears it", async () => {
+ expect(gitPausedFor()).toBe(0);
+
+ for (let i = 0; i < 3; i++) await expect(exhausted()).rejects.toThrow(/thread failed to start/);
+
+ // The breaker is open: git is not spawned at all, so the retry cannot cost a fork we don't have.
+ expect(gitPausedFor()).toBeGreaterThan(0);
+ let spawned = false;
+ await expect(
+ runGit(async () => {
+ spawned = true;
+ }),
+ ).rejects.toBeInstanceOf(GitUnavailableError);
+ expect(spawned).toBe(false);
+ // Periodic work backs off quietly rather than throwing into the pull loop.
+ expect(await tryRunGit(async () => "nope")).toBe(SKIPPED);
+
+ // Reopening is time-based; reach in rather than sleep five minutes for it.
+ const s = (globalThis as Record<symbol, { openUntil: number; exhaustions: number }>)[
+ Symbol.for("engram.git.queue")
+ ];
+ s.openUntil = Date.now() - 1;
+
+ expect(await runGit(async () => "back")).toBe("back");
+ expect(gitPausedFor()).toBe(0);
+ expect(s.exhaustions).toBe(0);
+ });
+
+ test("an ordinary git failure never trips it — only the host running out does", async () => {
+ for (let i = 0; i < 5; i++) {
+ await expect(runGit(async () => Promise.reject(new Error("CONFLICT (content): merge conflict")))).rejects.toThrow(
+ /CONFLICT/,
+ );
+ }
+ expect(gitPausedFor()).toBe(0);
+ });
+});
+
+describe("polled reads collapse onto one git process", () => {
+ test("callers within the TTL share one result, and an invalidation forces a fresh one", async () => {
+ invalidateGitReads();
+ let spawns = 0;
+ const read = () =>
+ gitRead("test:key", 10_000, async () => {
+ spawns++;
+ return spawns;
+ });
+
+ // Concurrent callers — the shape of several dashboard tabs polling /api/sync at once.
+ expect(await Promise.all([read(), read(), read()])).toEqual([1, 1, 1]);
+ expect(spawns).toBe(1);
+
+ // Sequential callers inside the TTL, the shape of one tab polling every 10s.
+ expect(await read()).toBe(1);
+ expect(spawns).toBe(1);
+
+ // A sync we ran ourselves changed the answer, so the next read must not be the stale one.
+ invalidateGitReads();
+ expect(await read()).toBe(2);
+ expect(spawns).toBe(2);
+ });
+
+ test("a failed read is not cached as the answer", async () => {
+ invalidateGitReads();
+ let attempts = 0;
+ const read = () =>
+ gitRead("test:flaky", 10_000, async () => {
+ attempts++;
+ if (attempts === 1) throw new Error("git status failed");
+ return "fine";
+ });
+
+ await expect(read()).rejects.toThrow("git status failed");
+ expect(await read()).toBe("fine");
+ });
+});
diff --git a/lib/git-queue.ts b/lib/git-queue.ts
new file mode 100644
index 0000000..a869aa6
--- /dev/null
+++ b/lib/git-queue.ts
@@ -0,0 +1,218 @@
+/**
+ * The single gate every git child process in this app passes through.
+ *
+ * WHY THE STATE LIVES ON `globalThis` AND NOT IN MODULE SCOPE
+ * ----------------------------------------------------------
+ * `lib/git.ts` is compiled into the server build several times over — the instrumentation entry
+ * (which owns the pull loop) gets its own copies, and the API routes get theirs, split across more
+ * than one chunk. Each copy got its own `let gitBusy`, its own `pending` array and its own debounce
+ * timer, so the "serialize git-sync" guard only ever serialized a caller against itself. Count the
+ * copies on any build:
+ *
+ * grep -rl 'engram.git.queue' .next/server/chunks # one file per copy of this module
+ *
+ * In production that means the 30s pull loop, an MCP note write and a folder write can each run
+ * `git pull --rebase` on the same clone at the same moment. Two consequences, both in the crash log:
+ *
+ * - Two fetches interleave their writes to `.git/FETCH_HEAD`, which ends up holding more than one
+ * merge candidate, and git dies with "Cannot rebase onto multiple branches." Three concurrent
+ * `git pull --rebase` in one clone reproduce it 40 times out of 40; serialized, 0 out of 40.
+ * Naming the remote and branch explicitly does NOT help — only one-at-a-time does.
+ * - The git children pile up — every pull forks git, then git-remote-https, which starts threads
+ * to resolve DNS — until the container is out of its process/thread budget. Then git reports
+ * "cannot fork() for remote-https: Resource temporarily unavailable" and "getaddrinfo() thread
+ * failed to start", libuv cannot start a thread either, and the runtime aborts: SIGABRT,
+ * restart, repeat. A *background sync* takes the whole service down.
+ *
+ * Keying off `globalThis` with `Symbol.for` makes the three copies share one queue, which is what
+ * the original fix intended. Every git invocation in the app — writes, pulls AND the read-only
+ * status/log/show commands the dashboard polls — goes through here, so "one git child at a time"
+ * is finally true rather than merely documented.
+ */
+
+/**
+ * Returned by `tryRunGit` when the queue was busy and the callback never ran.
+ *
+ * A Symbol, not `undefined`: the original guard returned `undefined` for "skipped", but a callback
+ * typed `Promise<void>` also resolves to `undefined`, so "we skipped" and "we ran and finished"
+ * were the same value. `runSync` therefore treated EVERY successful sync as a skip — it re-queued
+ * its reasons and rescheduled itself, forever. The vault's git history shows it plainly: on
+ * 2026-08-06 the commit subjects grew `1 change(s)` → `2` → `3` → `4` → `5`, each repeating every
+ * earlier reason, because `pending` never drained. A sentinel that cannot be produced by `fn`
+ * makes the two cases impossible to confuse.
+ *
+ * `Symbol.for`, not `Symbol`: with three copies of the calling module in one process, a fresh
+ * per-copy symbol would make `outcome === SKIPPED` false across a bundle boundary and resurrect
+ * exactly that bug. The global registry gives all three the same sentinel.
+ */
+export const SKIPPED = Symbol.for("engram.git.skipped");
+
+/** Thrown by `runGit` instead of spawning git while the breaker is open. */
+export class GitUnavailableError extends Error {
+ constructor(retryInMs: number) {
+ super(`git is paused for ${Math.ceil(retryInMs / 1000)}s — the container ran out of processes for it`);
+ this.name = "GitUnavailableError";
+ }
+}
+
+/** Consecutive fork/thread failures before we stop spawning git at all. */
+const TRIP_AFTER = 3;
+/** How long the breaker stays open. Long enough for whatever ate the process budget to let go. */
+const COOLDOWN_MS = 5 * 60_000;
+
+/**
+ * The failures that mean "this container cannot start another process or thread right now" —
+ * as opposed to "the network is down" or "the rebase conflicted". Retrying these immediately is
+ * what turns a resource blip into the crash loop, because each retry costs the fork we don't have.
+ */
+const EXHAUSTED =
+ /resource temporarily unavailable|thread failed to start|cannot fork|cannot allocate memory|\bEAGAIN\b|\bENOMEM\b/i;
+
+interface ReadSlot {
+ /** When `value` was produced (epoch ms). */
+ at: number;
+ value: unknown;
+ /** A read already on its way, so N concurrent callers share one git process instead of N. */
+ inFlight: Promise<unknown> | null;
+}
+
+interface QueueState {
+ /** Tail of the serial chain: a task awaits this before it may spawn git. Never rejects. */
+ tail: Promise<unknown>;
+ /**
+ * Enqueued-and-unsettled tasks that WRITE — a sync or a pull. Only these make `tryRunGit` skip.
+ *
+ * Counted separately from the reads deliberately. Everything queues, so no two git children ever
+ * overlap either way; but a 20ms `git status` for the sidebar must not be the reason a human's
+ * "sync now" click reports "nothing to do". Skipping is for the case that matters — a second
+ * writer piling onto the first — and waiting is fine for the rest.
+ */
+ writes: number;
+ /** Consecutive resource failures. Only a git command that SUCCEEDS resets it. */
+ exhaustions: number;
+ /** Epoch ms until which we refuse to spawn git. 0 when the breaker is closed. */
+ openUntil: number;
+ reads: Map<string, ReadSlot>;
+}
+
+const STATE_KEY = Symbol.for("engram.git.queue");
+type GlobalWithQueue = typeof globalThis & { [STATE_KEY]?: QueueState };
+
+function state(): QueueState {
+ const g = globalThis as GlobalWithQueue;
+ return (g[STATE_KEY] ??= {
+ tail: Promise.resolve(),
+ writes: 0,
+ exhaustions: 0,
+ openUntil: 0,
+ reads: new Map(),
+ });
+}
+
+const NOOP = () => {};
+
+function breakerOpen(s: QueueState): boolean {
+ if (s.openUntil === 0) return false;
+ if (s.openUntil > Date.now()) return true;
+ s.openUntil = 0; // cooldown elapsed — let the next command try
+ return false;
+}
+
+function trip(s: QueueState): void {
+ s.exhaustions++;
+ if (s.exhaustions < TRIP_AFTER || s.openUntil > Date.now()) return;
+ s.openUntil = Date.now() + COOLDOWN_MS;
+ console.error(
+ `[git] out of processes/threads for git ${s.exhaustions} times in a row — pausing all vault git for ` +
+ `${COOLDOWN_MS / 1000}s. The vault still serves from disk; it just stops syncing.`,
+ );
+}
+
+/** Run `fn`, minding the breaker and recording what its outcome says about the host. */
+async function guarded<T>(fn: () => Promise<T>): Promise<T> {
+ const s = state();
+ // Checked here rather than at enqueue time so a task that queued before the breaker opened
+ // still doesn't get to spawn git after it.
+ if (breakerOpen(s)) throw new GitUnavailableError(s.openUntil - Date.now());
+ try {
+ const out = await fn();
+ s.exhaustions = 0;
+ s.openUntil = 0;
+ return out;
+ } catch (e) {
+ if (EXHAUSTED.test(e instanceof Error ? e.message : String(e))) trip(s);
+ throw e;
+ }
+}
+
+function enqueue<T>(fn: () => Promise<T>, isWrite: boolean): Promise<T> {
+ const s = state();
+ // Synchronously, before any await: two tryRunGit calls in one tick must not both see zero.
+ if (isWrite) s.writes++;
+ const result = s.tail.then(() => guarded(fn)).finally(() => {
+ if (isWrite) s.writes--;
+ });
+ // The chain must survive a failing task: everything queued behind a rejection still has to run.
+ s.tail = result.then(NOOP, NOOP);
+ return result;
+}
+
+/**
+ * Wait for the git queue, then run `fn`. Use for work that must happen — reads, clones.
+ * Rejects with `GitUnavailableError` (without spawning anything) while the breaker is open.
+ */
+export function runGit<T>(fn: () => Promise<T>): Promise<T> {
+ return enqueue(fn, false);
+}
+
+/**
+ * Run `fn` unless another writer is already in flight, in which case return `SKIPPED` without
+ * running it. Use for the vault-mutating work — a pull or a debounced sync — where a skipped tick
+ * costs nothing because the next one is already scheduled, and where queueing a second writer
+ * would just stack git processes on top of the first under load.
+ */
+export function tryRunGit<T>(fn: () => Promise<T>): Promise<T | typeof SKIPPED> {
+ const s = state();
+ if (s.writes > 0 || breakerOpen(s)) return Promise.resolve(SKIPPED);
+ return enqueue(fn, true);
+}
+
+/**
+ * Serve a read-only git command from a short-lived cache, and collapse concurrent callers onto one
+ * git process. The dashboard polls `/api/sync` every 10s and `/api/activity` every 15s from the
+ * sidebar — per open tab — and every one of those was two-plus unserialized git children before.
+ */
+export function gitRead<T>(key: string, ttlMs: number, fn: () => Promise<T>): Promise<T> {
+ const reads = state().reads;
+ const slot = reads.get(key);
+ if (slot) {
+ if (Date.now() - slot.at < ttlMs) return Promise.resolve(slot.value as T);
+ if (slot.inFlight) return slot.inFlight as Promise<T>;
+ }
+ const fresh: ReadSlot = slot ?? { at: 0, value: undefined, inFlight: null };
+ fresh.inFlight = runGit(fn).then(
+ (v) => {
+ fresh.at = Date.now();
+ fresh.value = v;
+ fresh.inFlight = null;
+ return v;
+ },
+ (e) => {
+ fresh.inFlight = null;
+ throw e;
+ },
+ );
+ reads.set(key, fresh);
+ return fresh.inFlight as Promise<T>;
+}
+
+/** Drop the read cache. Called after we ourselves commit, pull or push — the answers just changed. */
+export function invalidateGitReads(): void {
+ state().reads.clear();
+}
+
+/** Milliseconds until git is allowed again, or 0 when it is allowed now. For reporting. */
+export function gitPausedFor(): number {
+ const s = state();
+ return breakerOpen(s) ? s.openUntil - Date.now() : 0;
+}
diff --git a/lib/git.test.ts b/lib/git.test.ts
index c257bf7..997534a 100644
--- a/lib/git.test.ts
+++ b/lib/git.test.ts
@@ -251,6 +251,41 @@ describe("a pull never rebases over uncommitted vault writes", () => {
});
});
+describe("one writer, across every copy of this module", () => {
+ /**
+ * Next.js compiles lib/git.ts into three server chunks — the instrumentation entry that owns the
+ * pull loop, the shared API-route chunk, and /api/folders. Module-level `let pending` / `let
+ * timer` therefore gave each of them its own debounce queue, so a note write and a folder write
+ * in the same 2.5s window each started their own commit → pull → push against one clone. Two
+ * concurrent `git pull --rebase` on one repo is what produced "Cannot rebase onto multiple
+ * branches." in the Railway log (reproduced 40/40; see lib/git-queue.test.ts). Holding the state
+ * on globalThis is what makes the three copies one writer.
+ */
+ test("the debounce queue is shared process state, not module state", async () => {
+ requestSync("Agent Yang: append delivery.md");
+ const shared = (globalThis as Record<symbol, { pending: string[] } | undefined>)[Symbol.for("engram.git.sync")];
+ expect(shared?.pending).toContain("Agent Yang: append delivery.md");
+ expect(pendingReasons()).toEqual(shared!.pending);
+ await syncNow(); // drain, so the 2.5s timer can't fire into a later test
+ expect(pendingReasons()).toEqual([]);
+ });
+
+ test("overlapping pulls and syncs never race into 'Cannot rebase onto multiple branches'", async () => {
+ fs.appendFileSync(path.join(VAULT, NOTE), "- **2026-08-07** — concurrent-callers entry.\n");
+ const results = await Promise.all([pullActive(), syncNow(), pullActive(), syncNow(), pullActive()]);
+
+ for (const r of results) {
+ expect(r?.error ?? "").not.toMatch(/multiple branches/);
+ }
+ // Whoever won the queue, the write is committed and the repo is left on its branch, not
+ // half-rebased. The losers skipped rather than piling a second git process onto the first.
+ expect(onDisk()).toContain("concurrent-callers entry.");
+ const status = await vaultGit().status();
+ expect(status.current).toBe(BRANCH);
+ expect(status.conflicted).toEqual([]);
+ });
+});
+
describe("sync failures are reportable, not just console noise", () => {
test("syncStatus surfaces a stranded stash so old autostash losses can be recovered", async () => {
await syncNow();
diff --git a/lib/git.ts b/lib/git.ts
index 2385280..031d267 100644
--- a/lib/git.ts
+++ b/lib/git.ts
@@ -1,46 +1,48 @@
import fs from "node:fs";
import path from "node:path";
-import { simpleGit } from "simple-git";
+import { simpleGit, type StatusResult } from "simple-git";
+import { SKIPPED, gitPausedFor, gitRead, invalidateGitReads, runGit, tryRunGit } from "@/lib/git-queue";
import { activeVaultDir, getActive } from "@/lib/repos";
import { gitAuthor, gitSyncEnabled } from "@/lib/settings";
import { rebuildIndex } from "@/lib/vault/store";
-let timer: ReturnType<typeof setTimeout> | null = null;
-let pending: string[] = [];
-
/**
- * A single in-flight guard shared by BOTH the write-sync (runSync) and the pull loop (pullActive),
- * so at most one git operation ever touches the vault repo at a time. Two concurrent git ops on one
- * repo mean index.lock contention and half-finished rebases; worse, under load the piled-up child
- * processes exhaust the container's fork()/thread budget, which makes libuv abort the whole process
- * (the SIGABRT + "getaddrinfo() thread failed to start" crash loop). Serializing pins the live git
- * subprocess count at one. If the lock is held, the caller skips (pull loop) or reschedules
- * (write-sync) instead of stacking more work on top.
+ * The debounce queue and the pull loop, on `globalThis` for the same reason the git queue is
+ * (see lib/git-queue.ts): this module is compiled into several server chunks, so a plain `let`
+ * gives the instrumentation entry and each group of API routes a copy of its own. Several
+ * `pending` arrays and several 2.5s debounce timers meant a note write and a folder write in the
+ * same window each started their own commit → pull → push cycle against one clone. Sharing the
+ * state is what makes the single-writer guarantee hold across route boundaries.
*/
-let gitBusy = false;
+interface SyncState {
+ timer: ReturnType<typeof setTimeout> | null;
+ pending: string[];
+ /** The last thing that went wrong in a sync, surfaced by syncStatus() instead of only console. */
+ lastError?: string;
+ pullTimer: ReturnType<typeof setTimeout> | null;
+ /** Consecutive pull failures — drives the loop's exponential backoff. */
+ pullFailures: number;
+}
+
+const SYNC_KEY = Symbol.for("engram.git.sync");
+type GlobalWithSync = typeof globalThis & { [SYNC_KEY]?: SyncState };
+
+function syncState(): SyncState {
+ const g = globalThis as GlobalWithSync;
+ return (g[SYNC_KEY] ??= { timer: null, pending: [], pullTimer: null, pullFailures: 0 });
+}
/**
- * Returned when the lock was held and `fn` never ran.
+ * How long a `syncStatus()` / `vaultActivity()` answer may be reused.
*
- * A Symbol, not `undefined`: the original guard returned `undefined` for "skipped", but a callback
- * typed `Promise<void>` also resolves to `undefined`, so "we skipped" and "we ran and finished"
- * were the same value. `runSync` therefore treated EVERY successful sync as a skip — it re-queued
- * its reasons and rescheduled itself, forever. The vault's git history shows it plainly: on
- * 2026-08-06 the commit subjects grew `1 change(s)` → `2` → `3` → `4` → `5`, each repeating every
- * earlier reason, because `pending` never drained. A sentinel that cannot be produced by `fn`
- * makes the two cases impossible to confuse.
+ * These are the polled endpoints: the sidebar's workspace switcher refreshes `/api/sync` every
+ * 10s and the dashboard refreshes `/api/activity` every 15s, per open tab. `syncStatus` alone was
+ * two git children (`status` + `stash list`) every time, none of them serialized against the pull
+ * and push that actually matter. Answers this fresh are indistinguishable to the reader and cost
+ * one git process instead of one per tab. Any sync we run ourselves clears the cache immediately.
*/
-const SKIPPED = Symbol("git-busy");
-
-async function withGitLock<T>(fn: () => Promise<T>): Promise<T | typeof SKIPPED> {
- if (gitBusy) return SKIPPED;
- gitBusy = true;
- try {
- return await fn();
- } finally {
- gitBusy = false;
- }
-}
+const STATUS_TTL_MS = 4_000;
+const ACTIVITY_TTL_MS = 8_000;
/**
* The vault dir ONLY when it's safe to run git there: it must be its OWN repo root (a `.git`
@@ -92,11 +94,51 @@ function gitEnv(name: string, email: string): Record<string, string> {
/**
* A git client for the vault with the sanitised environment already applied — to EVERY command,
* not just the commit. Pull and push spawn child processes through the same guard, so an
- * inherited `GIT_ASKPASS` broke them exactly as it broke commits.
+ * inherited `GIT_ASKPASS` broke them exactly as it broke commits. The read-only paths below use
+ * this client too: `GIT_DIR` or `GIT_WORK_TREE` inherited from the host would point `log` and
+ * `show` at some other repository and quietly serve its history as the vault's.
*/
function vaultGit(dir: string) {
const { name, email } = gitAuthor();
- return simpleGit(dir).env(gitEnv(name, email));
+ return simpleGit(dir, {
+ // The queue in lib/git-queue.ts already guarantees one git child at a time; this shuts the
+ // door simple-git leaves open by default (five), so no single client can widen it again.
+ maxConcurrentProcesses: 1,
+ // Kill a command that has printed nothing for two minutes rather than let it hold the queue
+ // — and its git / git-remote-https / resolver threads — indefinitely. A vault is markdown:
+ // two minutes of silence means the network is wedged, and wedged children that never exit
+ // are how the container ran out of processes to fork in the first place.
+ timeout: { block: 120_000 },
+ }).env(gitEnv(name, email));
+}
+
+/**
+ * The `<remote> <branch>` a pull names explicitly, or null when HEAD is detached.
+ *
+ * This is NOT what fixes "Cannot rebase onto multiple branches." — that error comes from two
+ * fetches racing on `.git/FETCH_HEAD`, and it reproduces just as reliably with an explicit
+ * refspec as without one (40/40 rounds either way against a local remote). Only serializing git
+ * prevents it; see lib/git-queue.ts.
+ *
+ * Naming the refspec buys two smaller things. A bare `git pull --rebase` needs the current branch
+ * to have tracking config, which a self-hosted VAULT_DIR repo (see gitVaultDir) may not have —
+ * that fails with "There is no tracking information for the current branch", where falling back
+ * to `origin/<current>` just works. And a detached HEAD gets a message naming the vault instead
+ * of git's generic "You are not currently on a branch".
+ */
+function upstreamOf(status: StatusResult): { remote: string; branch: string } | null {
+ if (status.detached || !status.current) return null;
+ const slash = status.tracking?.indexOf("/") ?? -1;
+ if (status.tracking && slash > 0) {
+ // Only the FIRST slash separates them — `origin/feature/x` is remote `origin`, branch `feature/x`.
+ return { remote: status.tracking.slice(0, slash), branch: status.tracking.slice(slash + 1) };
+ }
+ return { remote: "origin", branch: status.current };
+}
+
+async function pullRebase(g: ReturnType<typeof vaultGit>, up: ReturnType<typeof upstreamOf>): Promise<void> {
+ if (!up) throw new Error("vault HEAD is detached — refusing to pull; check out a branch in the vault clone first");
+ await g.pull(["--rebase", up.remote, up.branch]);
}
/**
@@ -105,9 +147,10 @@ function vaultGit(dir: string) {
*/
export function requestSync(reason: string): void {
if (!gitSyncEnabled() || !gitVaultDir()) return;
- pending.push(reason);
- if (timer) clearTimeout(timer);
- timer = setTimeout(runSync, 2500);
+ const s = syncState();
+ s.pending.push(reason);
+ if (s.timer) clearTimeout(s.timer);
+ s.timer = setTimeout(runSync, 2500);
}
export interface SyncOutcome {
@@ -119,8 +162,6 @@ export interface SyncOutcome {
error?: string;
}
-/** The last thing that went wrong in a sync, surfaced by syncStatus() instead of only console. */
-let lastSyncError: string | undefined;
const errText = (e: unknown) => (e instanceof Error ? e.message : String(e));
/**
@@ -171,7 +212,7 @@ async function syncOnce(reasons: string[]): Promise<SyncOutcome> {
// gap, `git pull --rebase` refuses on a dirty tree, which loses nothing; the next tick retries.
const before = await g.revparse(["HEAD"]).catch(() => "");
try {
- await g.pull(["--rebase"]);
+ await pullRebase(g, upstreamOf(status)); // committing does not move the branch or its upstream
out.pulled = true;
const after = await g.revparse(["HEAD"]).catch(() => "");
// A rebase that replayed our commit over remote work rewrote the tree; the index must
@@ -205,66 +246,80 @@ async function syncOnce(reasons: string[]): Promise<SyncOutcome> {
}
async function runSync(): Promise<void> {
- const reasons = pending;
- pending = [];
- const outcome = await withGitLock(() => syncOnce(reasons));
+ const s = syncState();
+ const reasons = s.pending;
+ s.pending = [];
+ s.timer = null; // this timer has fired; anything scheduled during the await is a new one
+ const outcome = await tryRunGit(() => syncOnce(reasons));
if (outcome === SKIPPED) {
- // The lock was held by a pull. The changed files are still dirty on disk, so don't drop them:
+ // Git was busy with a pull. The changed files are still dirty on disk, so don't drop them:
// re-queue the reasons and retry once the repo is free.
- pending.unshift(...reasons);
- if (timer) clearTimeout(timer);
- timer = setTimeout(runSync, 2500);
+ s.pending.unshift(...reasons);
+ if (s.timer) clearTimeout(s.timer);
+ s.timer = setTimeout(runSync, 2500);
return;
}
- lastSyncError = outcome.error;
+ s.lastError = outcome.error;
+ invalidateGitReads();
}
/** Run the debounced sync immediately. Returns SKIPPED-as-null when a pull holds the repo. */
export async function syncNow(reason = "manual sync"): Promise<SyncOutcome | null> {
if (!gitSyncEnabled() || !gitVaultDir()) return null;
- const reasons = pending.length > 0 ? pending : [reason];
- pending = [];
- if (timer) clearTimeout(timer);
- timer = null;
- const outcome = await withGitLock(() => syncOnce(reasons));
+ const s = syncState();
+ const reasons = s.pending.length > 0 ? s.pending : [reason];
+ s.pending = [];
+ if (s.timer) clearTimeout(s.timer);
+ s.timer = null;
+ const outcome = await tryRunGit(() => syncOnce(reasons));
if (outcome === SKIPPED) {
- pending.unshift(...reasons);
+ s.pending.unshift(...reasons);
return null;
}
- lastSyncError = outcome.error;
+ s.lastError = outcome.error;
+ invalidateGitReads();
return outcome;
}
/** Test seam: the reasons still waiting to be committed. */
export function pendingReasons(): string[] {
- return [...pending];
+ return [...syncState().pending];
}
export async function syncStatus() {
const dir = gitVaultDir();
if (!dir || !gitSyncEnabled()) return { enabled: false as const };
+ const s = syncState();
+ // Surfaced rather than hidden behind a generic error: when the breaker is open the dashboard's
+ // "sync error" dot is telling the truth, but only this says the vault is fine and git is paused.
+ const pausedMs = gitPausedFor();
+ const paused = pausedMs > 0 ? { paused: Math.ceil(pausedMs / 1000) } : {};
try {
- const g = vaultGit(dir);
- const s = await g.status();
- // Stash entries are reported because nothing in Engram creates one any more. Any that exist
- // are vault content the old `--autostash` pull stranded — recoverable with `git stash list`
- // / `git stash pop`, but invisible until someone is told it is there.
- const stashed = await g
- .stashList()
- .then((l) => l.total)
- .catch(() => 0);
+ const { st, stashed } = await gitRead(`status:${dir}`, STATUS_TTL_MS, async () => {
+ const g = vaultGit(dir);
+ const st = await g.status();
+ // Stash entries are reported because nothing in Engram creates one any more. Any that exist
+ // are vault content the old `--autostash` pull stranded — recoverable with `git stash list`
+ // / `git stash pop`, but invisible until someone is told it is there.
+ const stashed = await g
+ .stashList()
+ .then((l) => l.total)
+ .catch(() => 0);
+ return { st, stashed };
+ });
return {
enabled: true as const,
- dirty: s.files.length,
- ahead: s.ahead,
- behind: s.behind,
- branch: s.current,
- pending: pending.length,
+ dirty: st.files.length,
+ ahead: st.ahead,
+ behind: st.behind,
+ branch: st.current,
+ pending: s.pending.length,
...(stashed > 0 ? { stashed } : {}),
- ...(lastSyncError ? { lastError: lastSyncError } : {}),
+ ...paused,
+ ...(s.lastError ? { lastError: s.lastError } : {}),
};
} catch {
- return { enabled: true as const, error: true };
+ return { enabled: true as const, error: true, ...paused };
}
}
@@ -287,7 +342,7 @@ export interface PullResult {
export async function pullActive(): Promise<PullResult> {
const active = getActive();
if (!active) return { ok: true, changed: false };
- const result = await withGitLock(async (): Promise<PullResult> => {
+ const result = await tryRunGit(async (): Promise<PullResult> => {
const dir = activeVaultDir();
try {
const g = vaultGit(dir);
@@ -303,7 +358,8 @@ export async function pullActive(): Promise<PullResult> {
// the note is reverted, the writes live only in a stash nobody reads, and every caller was
// already told `ok: true`. Committing first (below) is strictly better than stashing: the
// content is in history either way, and a commit is a place people look.
- const dirty = (await g.status()).files.length > 0;
+ const status = await g.status();
+ const dirty = status.files.length > 0;
if (dirty) {
if (gitSyncEnabled()) {
// The write-sync commits, then pulls, then pushes. Let it own this cycle.
@@ -318,7 +374,7 @@ export async function pullActive(): Promise<PullResult> {
}
const before = await g.revparse(["HEAD"]).catch(() => "");
- await g.pull(["--rebase"]); // pull already fetches — a separate g.fetch() only doubles the child processes
+ await pullRebase(g, upstreamOf(status)); // pull already fetches — a separate g.fetch() only doubles the child processes
const after = await g.revparse(["HEAD"]).catch(() => "");
const changed = before !== after;
if (changed) rebuildIndex();
@@ -336,7 +392,9 @@ export async function pullActive(): Promise<PullResult> {
}
});
// SKIPPED = a sync was already in flight; a skipped tick is not an error.
- return result === SKIPPED ? { ok: true, changed: false } : result;
+ if (result === SKIPPED) return { ok: true, changed: false };
+ invalidateGitReads();
+ return result;
}
export interface ActivityEntry {
@@ -356,7 +414,7 @@ export async function vaultActivity(maxCount = 50): Promise<ActivityEntry[]> {
const dir = gitVaultDir();
if (!dir) return [];
try {
- const log = await simpleGit(dir).log({ maxCount });
+ const log = await gitRead(`activity:${dir}:${maxCount}`, ACTIVITY_TTL_MS, () => vaultGit(dir).log({ maxCount }));
return log.all.map((c) => ({
hash: c.hash.slice(0, 7),
message: c.message,
@@ -440,11 +498,17 @@ export async function commitChanges(hash: string): Promise<CommitDetail | null>
if (!dir) return null;
if (!/^[0-9a-f]{4,40}$/i.test(hash)) return null; // avoid passing arbitrary args to git
try {
- const g = simpleGit(dir);
- const meta = await g.raw(["show", "-s", "--no-color", "--format=%h%x1f%an%x1f%aI%x1f%s", hash]);
+ // All three `show`s in one queue slot: they describe a single commit, so interleaving another
+ // caller's pull between them would be three git children racing a rebase for no benefit.
+ const { meta, nameStatus, rawDiff } = await runGit(async () => {
+ const g = vaultGit(dir);
+ return {
+ meta: await g.raw(["show", "-s", "--no-color", "--format=%h%x1f%an%x1f%aI%x1f%s", hash]),
+ nameStatus: await g.raw(["show", "--no-color", "--format=", "--name-status", hash]),
+ rawDiff: await g.raw(["show", "--no-color", "--format=", "--patch", hash]),
+ };
+ });
const [shortHash, author, date, message] = meta.trim().split("\x1f");
- const nameStatus = await g.raw(["show", "--no-color", "--format=", "--name-status", hash]);
- const rawDiff = await g.raw(["show", "--no-color", "--format=", "--patch", hash]);
const truncated = rawDiff.length > MAX_DIFF;
const blocks = splitDiffByFile(truncated ? rawDiff.slice(0, MAX_DIFF) : rawDiff);
@@ -465,23 +529,25 @@ export async function commitChanges(hash: string): Promise<CommitDetail | null>
}
}
-let pullTimer: ReturnType<typeof setTimeout> | null = null;
/**
* Poll the remote for the active vault so the brain stays fresh without a redeploy. Self-reschedules
* instead of using setInterval: the next tick is queued only after the current pull settles, so a
* slow pull can never overlap the next one. On failure it backs off exponentially (30s healthy →
* capped ~16min) so a network/DNS blip can't become a tight retry loop that spawns git processes
* faster than they exit — the pile-up that aborted the process.
+ *
+ * The timer and the failure count live in the shared state, so the loop stays single even though
+ * this module exists three times over in the server build.
*/
export function startPullLoop(baseMs = 30_000): void {
- if (pullTimer) return;
- let failures = 0;
+ const s = syncState();
+ if (s.pullTimer) return;
const tick = async () => {
const res = await pullActive().catch(() => ({ ok: false as const }));
- failures = res.ok ? 0 : Math.min(failures + 1, 5);
- pullTimer = setTimeout(tick, baseMs * 2 ** failures);
- pullTimer.unref?.();
+ s.pullFailures = res.ok ? 0 : Math.min(s.pullFailures + 1, 5);
+ s.pullTimer = setTimeout(tick, baseMs * 2 ** s.pullFailures);
+ s.pullTimer.unref?.();
};
- pullTimer = setTimeout(tick, baseMs);
- pullTimer.unref?.();
+ s.pullTimer = setTimeout(tick, baseMs);
+ s.pullTimer.unref?.();
}
diff --git a/lib/repos.ts b/lib/repos.ts
index efaa008..b03cd08 100644
--- a/lib/repos.ts
+++ b/lib/repos.ts
@@ -4,6 +4,10 @@ import path from "node:path";
import { simpleGit } from "simple-git";
import { DATA_ROOT, VAULT_DIR } from "@/lib/config";
import { decryptSecret, encryptSecret } from "@/lib/crypto";
+// The clones go through the same queue as every other git command (see lib/git-queue.ts). A clone
+// is the heaviest git operation there is, and the boot path runs one at the moment Next.js is at
+// peak memory — exactly when an unserialized second git process is what tips the container over.
+import { runGit } from "@/lib/git-queue";
const REPOS_FILE = path.join(DATA_ROOT, "repos.json");
const VAULTS_DIR = path.join(DATA_ROOT, "vaults");
@@ -90,7 +94,7 @@ export async function addRepo(opts: {
const dir = vaultDirFor(id);
fs.rmSync(dir, { recursive: true, force: true });
- await simpleGit().clone(authedUrl(opts.url, opts.token), dir);
+ await runGit(() => simpleGit().clone(authedUrl(opts.url, opts.token), dir));
const rec: StoredRepo = {
id,
@@ -142,7 +146,7 @@ export async function ensureActiveCloned(): Promise<void> {
if (fs.existsSync(path.join(dir, ".git"))) return;
try {
fs.rmSync(dir, { recursive: true, force: true });
- await simpleGit().clone(authedUrl(a.url, a.tokenEnc ? decryptSecret(a.tokenEnc) : undefined), dir);
+ await runGit(() => simpleGit().clone(authedUrl(a.url, a.tokenEnc ? decryptSecret(a.tokenEnc) : undefined), dir));
} catch (e) {
console.error("[repos] re-clone failed", e);
}