Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Environment:0xK3vin MegaMemory libsql

From Leeroopedia
Knowledge Sources
Domains Infrastructure, Database
Last Updated 2026-10-27 14:00 GMT

Overview

libsql (SQLite-compatible) database with WAL mode, foreign keys, and busy_timeout for the MegaMemory knowledge graph storage layer.

Description

MegaMemory persists all knowledge graph data (concepts, edges, timeline) in a single libsql database file at `.megamemory/knowledge.db`. The `libsql` npm package (>= 0.5.22) provides a SQLite-compatible synchronous API similar to `better-sqlite3`. The database is configured with four critical PRAGMAs at construction time: `journal_mode = WAL` (write-ahead logging for concurrent readers), `foreign_keys = ON` (referential integrity), `busy_timeout = 5000` (5-second lock wait), and `synchronous = NORMAL` (balanced durability/performance). The schema is versioned (currently `SCHEMA_VERSION = 4`) with incremental migrations wrapped in `BEGIN IMMEDIATE` transactions.

Usage

Use this environment for all database operations in MegaMemory:

  • MCP server graph reads/writes (`understand`, `create_concept`, `update_concept`, `link`, `remove_concept`)
  • Merge operations (`MergeEngine`, `merge`/`conflicts`/`resolve` CLI)
  • Web graph explorer queries and timeline reconstruction
  • Multi-process concurrency (multiple agents writing to the same database)

System Requirements

Category Requirement Notes
OS Linux, macOS, or Windows libsql ships prebuilt binaries for major platforms
Hardware Any CPU No GPU required
Disk ~1-10MB per project Grows with number of concepts and embeddings (384-dim float32 per node)

Dependencies

System Packages

npm Packages

  • `libsql` >= 0.5.22

Credentials

No credentials required. The database is a local file with no authentication.

Quick Install

# libsql is installed automatically with megamemory
npm install megamemory

# Or install libsql directly
npm install libsql@^0.5.22

Code Evidence

Database initialization with PRAGMA configuration from `src/db.ts:19-24`:

this.db = new Database(dbPath);
this.db.pragma("journal_mode = WAL");
this.db.pragma("foreign_keys = ON");
this.db.pragma("busy_timeout = 5000");
this.db.pragma("synchronous = NORMAL");
this.migrate();

libsql import and pragma return handling from `src/db.ts:1-8` and `src/db.ts:28-34`:

import Database from "libsql";

// libsql returns { user_version: N } instead of raw N like better-sqlite3
return (
  typeof pragmaResult === "object" && pragmaResult !== null
    ? (pragmaResult as Record<string, unknown>).user_version
    : pragmaResult
) as number;

Schema version and migration guard from `src/db.ts:6` and `src/db.ts:37-48`:

const SCHEMA_VERSION = 4;

private migrate(): void {
  const version = this.getUserVersion();
  if (version >= SCHEMA_VERSION) return;

  this.db.exec("BEGIN IMMEDIATE");
  try {
    // Re-check after acquiring the write lock in case another process migrated first.
    const currentVersion = this.getUserVersion();
    if (currentVersion >= SCHEMA_VERSION) {
      this.db.exec("COMMIT");
      return;
    }

Concurrency retry with exponential backoff from `src/db.ts:209-225`:

runWithRetry<T>(fn: () => T, maxRetries = 3): T {
  for (let attempt = 0; ; attempt++) {
    try {
      return fn();
    } catch (err: unknown) {
      const isBusy =
        err instanceof Error &&
        (err.message.includes("SQLITE_BUSY") ||
          err.message.includes("database is locked"));
      if (!isBusy || attempt >= maxRetries) {
        throw err;
      }
      const delayMs = 50 * Math.pow(2, attempt);
      Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delayMs);
    }
  }
}

Common Errors

Error Message Cause Solution
`SQLITE_BUSY: database is locked` Another process holds the write lock `busy_timeout=5000` + `runWithRetry` (3 retries, exponential backoff) handles this automatically
`FOREIGN KEY constraint failed` Edge references a non-existent node Ensure target node exists before inserting edges; `insertNodeAndEdges` checks `nodeExists` first
`UNIQUE constraint failed: edges` Duplicate edge (same from/to/relation) `INSERT OR IGNORE` in `insertEdge` handles this; unique index `idx_edges_unique` enforces deduplication
`user_version` returns object instead of number libsql pragma returns `{ user_version: N }` Handled in `getUserVersion()` with type check

Compatibility Notes

  • libsql vs better-sqlite3: libsql returns `{ user_version: N }` from pragma instead of a raw number. The code handles both forms in `getUserVersion()`.
  • libsql BLOB handling: libsql returns `ArrayBuffer` for BLOBs but expects `Buffer` when binding. The `toBuffer()` helper in `merge.ts` converts between them.
  • WAL mode: Enables concurrent readers during writes. Multiple MCP server processes can read simultaneously while one writes.
  • Multi-process: Designed for multiple coding agents writing to the same database. `BEGIN IMMEDIATE` + `busy_timeout` + `runWithRetry` handle contention.

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment