Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
refactor(storage): route Second Brain, bots queue, boards and pool cache through the SQLite driver
Salman Qureshi3db5ae60f2f2
diff --git a/src/bots/queue.test.ts b/src/bots/queue.test.tsindex 97a32343..e8238534 100644--- a/src/bots/queue.test.ts+++ b/src/bots/queue.test.ts@@ -63,7 +63,7 @@ function job(id: string, overrides: Partial<DurableBotJob> = {}): Omit<DurableBofunction makeBackends(dir: string) {return {json: new JsonFileQueueBackend(dir, 100),- sqlite: new SqliteQueueBackend(dir, 100, require('better-sqlite3')),+ sqlite: new SqliteQueueBackend(dir, 100),};}@@ -74,15 +74,11 @@ const openBackends: Array<{ close(): void }> = [];function mkBackend(name: 'json' | 'sqlite', dir: string, dlqCap = 100) {const backend = name === 'json'? new JsonFileQueueBackend(dir, dlqCap)- : new SqliteQueueBackend(dir, dlqCap, require('better-sqlite3'));+ : new SqliteQueueBackend(dir, dlqCap);openBackends.push(backend);return backend;}-// `require` equivalent for the test (ESM)-import { createRequire } from 'node:module';-const require = createRequire(import.meta.url);-describe('BotQueue backends (JSON-file + SQLite semantics)', () => {let root: string;diff --git a/src/bots/queue.ts b/src/bots/queue.tsindex 7d06f12e..7a538dc8 100644--- a/src/bots/queue.ts+++ b/src/bots/queue.ts@@ -1,37 +1,11 @@import { createHash, randomUUID } from 'node:crypto';-import { existsSync, mkdirSync, readFileSync, renameSync, rmSync } from 'node:fs';-import { createRequire } from 'node:module';+import { existsSync, mkdirSync, readFileSync, renameSync } from 'node:fs';import { join, resolve } from 'node:path';-import { tmpdir } from 'node:os';import { logger } from '../utils/logger.js';+import { isSqliteAvailable, openSqlite, type SqliteDatabase } from '../utils/sqlite-driver.js';import type { BotTrigger } from './types.js';-const require = createRequire(import.meta.url);--// Same availability probe as the second brain (src/memory/second-brain-db.ts):-// better-sqlite3 is a native module and may be absent on old Node or Termux.-let sqliteClass: (typeof import('better-sqlite3')) | null = null;-let probeDone = false;-function ensureSqliteProbed(): boolean {- if (probeDone) return sqliteClass !== null;- probeDone = true;- try {- const mod = require('better-sqlite3');- const probeDir = join(tmpdir(), `mercury-sqlite3-probe-${process.pid}`);- try {- mkdirSync(probeDir, { recursive: true });- const probeDb = new mod(join(probeDir, 'probe.db'));- probeDb.close();- rmSync(probeDir, { recursive: true, force: true });- sqliteClass = mod;- } catch {- sqliteClass = null;- }- } catch {- sqliteClass = null;- }- return sqliteClass !== null;-}+export const QUEUE_DB_FILE = 'queue.db';export interface DurableBotJob {id: string;@@ -142,7 +116,8 @@ function normalizeJob(raw: any): DurableBotJob {/*** Durable bot job queue — the "enqueue before ack" boundary- * (BOTS-ARCHITECTURE.md §2.6). Backend chain: native SQLite (better-sqlite3)+ * (BOTS-ARCHITECTURE.md §2.6). Backend chain: SQLite via the shared driver+ * (better-sqlite3 → bun:sqlite → node:sqlite, src/utils/sqlite-driver.ts)* → JSON-file lease store. Correctness never depends on SQLite: the queue is* single-writer (in-process BotManager), so durability (atomic rename +* fsync) and lease-expiry timestamp logic are all that is required.@@ -154,8 +129,8 @@ export class BotQueue {constructor(botsRoot: string, dlqCap: number = DLQ_CAP) {const path = resolve(botsRoot);- if (ensureSqliteProbed()) {- this.backend = new SqliteQueueBackend(path, dlqCap, sqliteClass!);+ if (isSqliteAvailable()) {+ this.backend = new SqliteQueueBackend(path, dlqCap);} else {this.backend = new JsonFileQueueBackend(path, dlqCap);}@@ -249,23 +224,26 @@ export class BotQueue {}// ----------------------------------------------------------------------------// Native SQLite backend (better-sqlite3, WAL)+// SQLite backend (shared driver, WAL)// ----------------------------------------------------------------------------type SqliteDb = import('better-sqlite3').Database;-export class SqliteQueueBackend implements BotQueueBackend {- readonly name = 'better-sqlite3';- private db: SqliteDatabase2;+ /** The engine name (`better-sqlite3`, `bun:sqlite`, `node:sqlite`). */+ readonly name: string;+ private db: SqliteDatabase;private dlqCap: number;// A disposed manager must never turn an in-flight turn's queue access into// a crash: post-close ops degrade to no-ops (an unsettled claim survives// via lease expiry and resumes on the next boot).private closed = false;- constructor(path: string, dlqCap: number, cls: (typeof import('better-sqlite3'))) {+ /** `db` lets tests hand in an already-open handle; otherwise `<path>/queue.db` is opened via the driver. */+ constructor(path: string, dlqCap: number, db?: SqliteDatabase) {mkdirSync(path, { recursive: true });- this.db = new cls(join(path, 'queue.db')) as unknown as SqliteDatabase2;+ const handle = db ?? openSqlite(join(path, QUEUE_DB_FILE));+ if (!handle) throw new Error('No SQLite engine available for the bot queue');+ this.db = handle;+ this.name = handle.backend;this.db.pragma('journal_mode = WAL');this.db.exec(`CREATE TABLE IF NOT EXISTS bot_jobs (@@ -472,19 +450,6 @@ export class SqliteQueueBackend implements BotQueueBackend {}}-// Minimal structural type for the better-sqlite3 API we use (avoids pulling-// the optional dep's types into the required build when it is absent).-interface SqliteDatabase2 {- pragma(source: string): void;- prepare(sql: string): {- run(...params: any[]): { changes: number | bigint };- get(...params: any[]): any;- all(...params: any[]): any[];- };- exec(sql: string): void;- close(): void;-}-// ---------------------------------------------------------------------------// JSON-file lease backend (zero native deps — Termux / old Node fallback)// ---------------------------------------------------------------------------diff --git a/src/cloud/pool-search.ts b/src/cloud/pool-search.tsindex cebd404a..75b54da3 100644--- a/src/cloud/pool-search.ts+++ b/src/cloud/pool-search.ts@@ -1,16 +1,10 @@import { join } from 'node:path';import { existsSync, mkdirSync } from 'node:fs';-import { createRequire } from 'node:module';import { getMemoryDir } from '../utils/config.js';import { logger } from '../utils/logger.js';+import { openSqlite, type SqliteDatabase } from '../utils/sqlite-driver.js';import { refreshToken } from './pairing.js';-type BetterSqlite3Database = import('better-sqlite3').Database;-const require = createRequire(import.meta.url);-function loadDatabase(): typeof import('better-sqlite3') {- return require('better-sqlite3');-}-/*** Cloud shared-pool search client for the agent.*@@ -58,24 +52,44 @@ interface CacheRow {fetched_at: number;}-let cacheDb: BetterSqlite3Database | null = null;+export const POOL_SEARCH_CACHE_FILE = 'pool-search-cache.db';++let cacheDb: SqliteDatabase | null = null;+let cacheDisabled = false;-function getCacheDb(): BetterSqlite3Database {+/**+ * The cache DB, or `null` when no SQLite engine is available (or the file+ * cannot be opened) — the search then runs uncached instead of failing.+ */+function getCacheDb(): SqliteDatabase | null {if (cacheDb) return cacheDb;- const dir = getMemoryDir();- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });- const dbPath = join(dir, 'pool-search-cache.db');- cacheDb = loadDatabase()(dbPath);- cacheDb.exec(`- CREATE TABLE IF NOT EXISTS pool_search_cache (- query_hash TEXT PRIMARY KEY,- query TEXT NOT NULL,- results_json TEXT NOT NULL,- fetched_at INTEGER NOT NULL- );- CREATE INDEX IF NOT EXISTS idx_pool_search_fetched_at ON pool_search_cache(fetched_at);- `);- return cacheDb;+ if (cacheDisabled) return null;+ try {+ const dir = getMemoryDir();+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });+ const dbPath = join(dir, POOL_SEARCH_CACHE_FILE);+ const db = openSqlite(dbPath);+ if (!db) {+ cacheDisabled = true;+ logger.debug('pool search cache disabled: no SQLite engine available');+ return null;+ }+ db.exec(`+ CREATE TABLE IF NOT EXISTS pool_search_cache (+ query_hash TEXT PRIMARY KEY,+ query TEXT NOT NULL,+ results_json TEXT NOT NULL,+ fetched_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS idx_pool_search_fetched_at ON pool_search_cache(fetched_at);+ `);+ cacheDb = db;+ return cacheDb;+ } catch (err) {+ cacheDisabled = true;+ logger.warn({ err }, 'pool search cache disabled: could not open cache database');+ return null;+ }}function hashQuery(query: string): string {@@ -89,6 +103,7 @@ function hashQuery(query: string): string {function readCache(queryHash: string): PoolSearchHit[] | null {const db = getCacheDb();+ if (!db) return null;const row = db.prepare('SELECT results_json, fetched_at FROM pool_search_cache WHERE query_hash = ?').get(queryHash) as CacheRow | undefined;if (!row) return null;if (Date.now() - row.fetched_at > CACHE_TTL_MS) return null;@@ -101,6 +116,7 @@ function readCache(queryHash: string): PoolSearchHit[] | null {function writeCache(queryHash: string, query: string, results: PoolSearchHit[]): void {const db = getCacheDb();+ if (!db) return;const now = Date.now();db.prepare('INSERT OR REPLACE INTO pool_search_cache (query_hash, query, results_json, fetched_at) VALUES (?, ?, ?, ?)').run(queryHash,diff --git a/src/core/board-db.test.ts b/src/core/board-db.test.tsnew file mode 100644index 00000000..54dfd946--- /dev/null+++ b/src/core/board-db.test.ts@@ -0,0 +1,83 @@+import { existsSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { BOARDS_DB_FILE, BOARDS_JSON_FILE, createBoardDB } from './board-db.js';+import { SQLITE_BACKEND_ENV, isSqliteAvailable, resetSqliteDriverForTests } from '../utils/sqlite-driver.js';+import type { Board, BoardContext } from '../types/agent.js';++function board(id: string, updatedAt: number): Board {+ return {+ id,+ name: `Board ${id}`,+ description: '',+ status: 'active',+ cards: [],+ createdAt: updatedAt,+ updatedAt,+ } as unknown as Board;+}++const savedHome = process.env.MERCURY_HOME;+const savedBackend = process.env[SQLITE_BACKEND_ENV];+let home: string;++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'mercury-board-db-'));+ process.env.MERCURY_HOME = home;+ resetSqliteDriverForTests();+});++afterEach(() => {+ if (savedHome === undefined) delete process.env.MERCURY_HOME;+ else process.env.MERCURY_HOME = savedHome;+ if (savedBackend === undefined) delete process.env[SQLITE_BACKEND_ENV];+ else process.env[SQLITE_BACKEND_ENV] = savedBackend;+ resetSqliteDriverForTests();+ rmSync(home, { recursive: true, force: true });+});++describe('BoardDB', () => {+ it.skipIf(!isSqliteAvailable())('uses SQLite when an engine is available and round-trips boards and contexts', () => {+ const db = createBoardDB();+ expect(db.kind).toBe('sqlite');+ expect(existsSync(join(home, 'memory', BOARDS_DB_FILE))).toBe(true);++ db.saveBoard(board('b1', 1_000));+ db.saveBoard(board('b2', 2_000));+ db.saveBoard({ ...board('b1', 3_000), name: 'renamed' });+ expect(db.loadAll().map((b) => b.id)).toEqual(['b1', 'b2']);+ expect(db.getBoard('b1')?.name).toBe('renamed');+ expect(db.getBoard('missing')).toBeUndefined();++ const context = { boardId: 'b1', events: [{ type: 'note', at: 1 }] } as unknown as BoardContext;+ db.saveContext('b1', context);+ expect(db.getContext('b1')).toEqual(context);+ expect(db.getContext('b2')).toBeUndefined();++ db.deleteBoard('b1');+ expect(db.getBoard('b1')).toBeUndefined();+ expect(db.getContext('b1')).toBeUndefined();+ expect(db.loadAll().map((b) => b.id)).toEqual(['b2']);++ // A second instance sees the committed state (no in-memory cache).+ const again = createBoardDB();+ expect(again.loadAll().map((b) => b.id)).toEqual(['b2']);+ });++ it('falls back to JSON files when storage is JSON-only', () => {+ process.env[SQLITE_BACKEND_ENV] = 'json';+ resetSqliteDriverForTests();+ const db = createBoardDB();+ expect(db.kind).toBe('json');+ db.saveBoard(board('j1', 10));+ db.saveContext('j1', { boardId: 'j1' } as unknown as BoardContext);+ db.flush();+ expect(existsSync(join(home, 'memory', BOARDS_JSON_FILE))).toBe(true);+ expect(existsSync(join(home, 'memory', BOARDS_DB_FILE))).toBe(false);++ const again = createBoardDB();+ expect(again.loadAll().map((b) => b.id)).toEqual(['j1']);+ expect(again.getContext('j1')).toEqual({ boardId: 'j1' });+ });+});diff --git a/src/core/board-db.ts b/src/core/board-db.tsindex 87461b83..85d5e6de 100644--- a/src/core/board-db.ts+++ b/src/core/board-db.ts@@ -2,9 +2,10 @@* Board Database Layer — Optimized Persistence with SQLite/JSON Fallback** Strategy:- * - Primary: SQLite (if better-sqlite3 available) — fast queries, ACID, FTS+ * - Primary: SQLite via the shared driver (better-sqlite3 → bun:sqlite →+ * node:sqlite, see src/utils/sqlite-driver.ts) — fast queries, ACID* - Fallback: JSON file with write batching and debounce — works everywhere- *+ ** The BoardManager can use this as its storage backend instead of raw JSON.*/@@ -12,10 +13,16 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { getMercuryHome } from '../utils/config.js';import { logger } from '../utils/logger.js';-import { isBetterSqlite3Available } from '../memory/second-brain-db.js';+import { isSqliteAvailable, openSqlite, type SqliteDatabase } from '../utils/sqlite-driver.js';import type { Board, BoardCard, BoardContext, BoardContextEvent } from '../types/agent.js';+export const BOARDS_DB_FILE = 'boards.db';+export const BOARDS_JSON_FILE = 'boards.json';+export const BOARD_CONTEXTS_JSON_FILE = 'board-contexts.json';+export interface BoardDB {+ /** `sqlite` (any engine) or `json`. */+ readonly kind: 'sqlite' | 'json';loadAll(): Board[];saveBoard(board: Board): void;deleteBoard(id: string): void;@@ -28,6 +35,7 @@ export interface BoardDB {// ── JSON Fallback (optimized with write debouncing) ──────────────class JSONBoardDB implements BoardDB {+ readonly kind = 'json' as const;private boards: Map<string, Board> = new Map();private contexts: Map<string, BoardContext> = new Map();private dirty = false;@@ -38,8 +46,8 @@ class JSONBoardDB implements BoardDB {constructor() {const dir = join(getMercuryHome(), 'memory');if (!existsSync(dir)) mkdirSync(dir, { recursive: true });- this.filePath = join(dir, 'boards.json');- this.contextPath = join(dir, 'board-contexts.json');+ this.filePath = join(dir, BOARDS_JSON_FILE);+ this.contextPath = join(dir, BOARD_CONTEXTS_JSON_FILE);this.loadFromDisk();}@@ -122,23 +130,27 @@ class JSONBoardDB implements BoardDB {// ── SQLite Backend (when available) ──────────────────────────────class SQLiteBoardDB implements BoardDB {- private db: any;+ readonly kind = 'sqlite' as const;+ private db: SqliteDatabase;constructor() {const dir = join(getMercuryHome(), 'memory');if (!existsSync(dir)) mkdirSync(dir, { recursive: true });- const dbPath = join(dir, 'boards.db');+ const dbPath = join(dir, BOARDS_DB_FILE);- // Dynamic require- const { createRequire } = require('node:module');- const req = createRequire(import.meta.url);- const Database = req('better-sqlite3');- this.db = new Database(dbPath);+ const db = openSqlite(dbPath);+ if (!db) throw new Error('No SQLite engine available');+ this.db = db;this.db.pragma('journal_mode = WAL');this.db.pragma('synchronous = NORMAL');this.initSchema();}+ /** Engine backing this database (`better-sqlite3`, `bun:sqlite`, `node:sqlite`). */+ get backend(): string {+ return this.db.backend;+ }+private initSchema(): void {this.db.exec(`CREATE TABLE IF NOT EXISTS boards (@@ -195,20 +207,26 @@ class SQLiteBoardDB implements BoardDB {let instance: BoardDB | null = null;-export function getBoardDB(): BoardDB {- if (!instance) {- if (isBetterSqlite3Available()) {- try {- instance = new SQLiteBoardDB();- logger.info('Board DB: using SQLite backend');- } catch (err) {- logger.warn({ err }, 'Board DB: SQLite init failed, falling back to JSON');- instance = new JSONBoardDB();- }- } else {- instance = new JSONBoardDB();- logger.info('Board DB: using JSON fallback (SQLite not available)');+/**+ * Build a fresh BoardDB for the current `MERCURY_HOME`: SQLite when any+ * engine is available, JSON otherwise. `getBoardDB()` memoizes one instance.+ */+export function createBoardDB(): BoardDB {+ if (isSqliteAvailable()) {+ try {+ const db = new SQLiteBoardDB();+ logger.info({ backend: db.backend }, 'Board DB: using SQLite backend');+ return db;+ } catch (err) {+ logger.warn({ err }, 'Board DB: SQLite init failed, falling back to JSON');+ return new JSONBoardDB();}}+ logger.info('Board DB: using JSON fallback (SQLite not available)');+ return new JSONBoardDB();+}++export function getBoardDB(): BoardDB {+ if (!instance) instance = createBoardDB();return instance;}diff --git a/src/memory/second-brain-db.ts b/src/memory/second-brain-db.tsindex 811b96c7..44a248f6 100644--- a/src/memory/second-brain-db.ts+++ b/src/memory/second-brain-db.ts@@ -1,43 +1,23 @@-import { existsSync, mkdirSync, rmSync } from 'node:fs';-import { dirname, join } from 'node:path';-import { tmpdir } from 'node:os';-import { createRequire } from 'node:module';+import { existsSync, mkdirSync } from 'node:fs';+import { dirname } from 'node:path';import { logger } from '../utils/logger.js';+import { isSqliteAvailable, openSqlite, type SqliteDatabase } from '../utils/sqlite-driver.js';-type BetterSqlite3Database = import('better-sqlite3').Database;--const require = createRequire(import.meta.url);--let syncDatabaseClass: typeof import('better-sqlite3') | null = null;-let availabilityChecked = false;-let available = false;--function ensureProbed(): void {- if (availabilityChecked) return;- availabilityChecked = true;- try {- const mod = require('better-sqlite3');- const probeDir = join(tmpdir(), `mercury-sqlite3-probe-${process.pid}`);- try {- mkdirSync(probeDir, { recursive: true });- const probeDb = new mod(join(probeDir, 'probe.db'));- probeDb.close();- rmSync(probeDir, { recursive: true, force: true });- syncDatabaseClass = mod;- available = true;- } catch {- syncDatabaseClass = null;- }- } catch {- syncDatabaseClass = null;- }-}-+/**+ * True when any SQLite engine is available (better-sqlite3, bun:sqlite or+ * node:sqlite — see `src/utils/sqlite-driver.ts`).+ * @deprecated The name predates the shared driver; prefer `isSqliteAvailable()`.+ */export function isBetterSqlite3Available(): boolean {- ensureProbed();- return syncDatabaseClass !== null;+ return isSqliteAvailable();}+export const SECOND_BRAIN_UNAVAILABLE_MESSAGE =+ 'No SQLite engine is available — second brain memory requires one. ' ++ 'Use Node >= 22.13 (built-in node:sqlite), a standalone Mercury binary (bun:sqlite), ' ++ 'or install build tools (make, gcc/g++, python3) and run `npm rebuild better-sqlite3`. ' ++ 'Run `mercury doctor --storage` for details.';+export interface MemoryRow {id: string;user_key: string;@@ -89,26 +69,25 @@ export interface PersonConnectionRow {}export class SecondBrainDB {- private db: BetterSqlite3Database;+ private db: SqliteDatabase;constructor(dbPath: string) {- ensureProbed();- if (!syncDatabaseClass) {- throw new Error(- 'better-sqlite3 is not available — second brain memory requires it. ' +- 'Install build tools (make, gcc/g++, python3) or upgrade to Node >= 20. ' +- 'See: https://github.com/WiseLibs/better-sqlite3/blob/master/docs/compilation.md'- );- }const dir = dirname(dbPath);if (!existsSync(dir)) {mkdirSync(dir, { recursive: true });}- this.db = new syncDatabaseClass(dbPath);+ const db = openSqlite(dbPath);+ if (!db) throw new Error(SECOND_BRAIN_UNAVAILABLE_MESSAGE);+ this.db = db;this.db.pragma('journal_mode = WAL');this.db.pragma('synchronous = NORMAL');}+ /** Engine backing this database: `better-sqlite3`, `bun:sqlite` or `node:sqlite`. */+ get backend(): string {+ return this.db.backend;+ }+init(): void {this.db.exec(`CREATE TABLE IF NOT EXISTS memories (@@ -242,7 +221,7 @@ export class SecondBrainDB {// Index for incremental fetch (shareable + updated_at — the cloud pull query).this.db.exec('CREATE INDEX IF NOT EXISTS idx_memories_shareable_updated ON memories(shareable, updated_at)');- logger.info('Second brain database initialized');+ logger.info({ backend: this.db.backend }, 'Second brain database initialized');}insert(row: Omit<MemoryRow, 'rowid'> & { rowid?: never }): void {