Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

20.2 KB
Raw Blame
import { randomUUID } from 'crypto';
import { constants, existsSync, renameSync as fsRenameSync, statSync, unlinkSync } from 'fs';
import { copyFile } from 'fs/promises';
import { dirname, join } from 'path';
import { Database } from 'bun:sqlite';
import { logger } from '../../utils/logger.js';
import { renameWithWindowsRetry } from '../../shared/atomic-json.js';
import { runSqliteFileJob, SqliteFileJobError } from './sqlite-file-job.js';
import { openRestoreStagingLock } from './snapshot-staging.js';
import { LATEST_SCHEMA_VERSION } from '../sqlite/connection.js';
import { ChromaSyncState } from '../sync/ChromaSyncState.js';
import { stageRestoreCatchUp } from '../sync/restore-catch-up.js';
import { contextCacheDir, listContextCacheFiles } from '../../shared/context-cache.js';
import {
  clearPendingRestore,
  readPendingRestore,
  resolveSnapshotInside,
  writeLastRestoreResult,
  type LastRestoreResult,
} from './snapshot-files.js';

const SIDECAR_EXTS = ['-wal', '-shm'] as const;

export interface SwapResult {
  preRestoreCopy: string | null;
}

export interface SwapOptions {
  /** Where the copy of the replaced database goes (a snapshot-named file, so it can be restored). */
  preRestoreDir: string;
  /** Test seam for the one step whose failure the swap must survive. */
  renameSync?: (from: string, to: string) => void;
  /**
   * How long to keep retrying while another process holds the live database
   * (0 = fail at once). See applyPendingRestore for where the window comes from.
   */
  busyRetryWindowMs?: number;
  /** The configured SyncHub, account and device for this restore. */
  restoreCatchUpScope?: string;
}

/** Pause between "in use" retries: short next to the retry window, long next to a checkpoint. */
const BUSY_RETRY_INTERVAL_MS = 500;

const IN_USE_MESSAGE = 'the database is in use by another process; stop it and retry the restore';

class DatabaseInUseError extends Error {}

/**
 * Checkpoint the live database in the child process. Throws DatabaseInUseError
 * when another connection holds it, and returns false when the file is too
 * damaged to checkpoint at all.
 */
async function checkpointLiveDatabase(dbPath: string): Promise<boolean> {
  try {
    const { busy } = await runSqliteFileJob({ kind: 'checkpoint', target: dbPath });
    if (busy) throw new DatabaseInUseError(IN_USE_MESSAGE);
    return true;
  } catch (error) {
    if (!(error instanceof SqliteFileJobError)) throw error;
    const code = error.code ?? '';
    // SQLITE_BUSY / SQLITE_LOCKED surface as thrown errors when another
    // connection holds a lock: that is "in use", not damage.
    if (/^SQLITE_(BUSY|LOCKED)(_|$)/.test(code)) {
      throw new DatabaseInUseError(`${IN_USE_MESSAGE} (${error.message})`);
    }
    if (!/^SQLITE_(CORRUPT|NOTADB)(_|$)/.test(code)) throw error;
    logger.warn('BACKUP', 'Live database could not be checkpointed; keeping its -wal with the pre-restore copy', {}, error);
    return false;
  }
}

/**
 * Hold SQLite's main-file lock from the pre-restore copy through the rename.
 * The child has already drained the WAL. If a writer got in before we took
 * the lock and left frames behind, let the next child drain them off-thread.
 */
function lockCheckpointedDatabase(dbPath: string): Database {
  const db = new Database(dbPath, { readwrite: true, create: false });
  try {
    db.exec('PRAGMA locking_mode = EXCLUSIVE; BEGIN EXCLUSIVE; ROLLBACK');
    if ((statSync(`${dbPath}-wal`, { throwIfNoEntry: false })?.size ?? 0) > 0) {
      throw new DatabaseInUseError(IN_USE_MESSAGE);
    }
    // In rollback mode, closing the lock on the old inode after the rename
    // cannot touch WAL sidecars that a connection to the replacement creates.
    db.exec('PRAGMA journal_mode = DELETE');
    // Hold an actual transaction across the copy and rename. Changing journal
    // modes can release the earlier lock even with locking_mode=EXCLUSIVE.
    db.exec('BEGIN EXCLUSIVE');
    const mode = db.query('PRAGMA journal_mode').get() as { journal_mode: string };
    if (mode.journal_mode !== 'delete') throw new DatabaseInUseError(IN_USE_MESSAGE);
    return db;
  } catch (error) {
    db.close();
    if (/^SQLITE_(BUSY|LOCKED)(_|$)/.test((error as { code?: string }).code ?? '')) {
      throw new DatabaseInUseError(IN_USE_MESSAGE);
    }
    throw error;
  }
}

async function checkpointWithRetry(dbPath: string, retryWindowMs: number): Promise<{
  checkpointed: boolean;
  liveLock: Database | null;
}> {
  const giveUpAt = Date.now() + retryWindowMs;
  for (;;) {
    try {
      const checkpointed = await checkpointLiveDatabase(dbPath);
      // Windows refuses to replace the open SQLite main file. Keep its
      // handle-free swap path, including the OS sharing checks.
      const liveLock = checkpointed && process.platform !== 'win32' ? lockCheckpointedDatabase(dbPath) : null;
      return { checkpointed, liveLock };
    } catch (error) {
      if (!(error instanceof DatabaseInUseError) || Date.now() + BUSY_RETRY_INTERVAL_MS > giveUpAt) throw error;
      await new Promise(resolve => setTimeout(resolve, BUSY_RETRY_INTERVAL_MS));
    }
  }
}

function removeIfPresent(path: string): void {
  if (existsSync(path)) unlinkSync(path);
}

function removeRestoreStagingFiles(files: string[]): void {
  for (const leftover of files) {
    try {
      removeIfPresent(leftover);
    } catch (error) {
      logger.warn('BACKUP', 'Could not remove restore staging file', { leftover }, error instanceof Error ? error : new Error(String(error)));
    }
  }
}

async function publishPreRestoreCopy(
  source: string,
  destination: string,
  { wal, sourceLocked = false }: { wal?: string; sourceLocked?: boolean } = {},
): Promise<void> {
  using lock = openRestoreStagingLock(dirname(destination));
  // A read transaction excludes cleanup until the staging claim is released.
  // Reading the schema actually takes the shared lock; BEGIN alone is deferred.
  // One second of busy_timeout: only removePartialSnapshots holds this lock
  // exclusively, across a few lstat and unlink calls. That whole call measured
  // 2.4 ms with 3 abandoned copies and 291 ms with 1,000 (2026-11-26, macOS,
  // machine under test load). A restore that still cannot take the lock fails
  // here, loudly, with the live database not yet replaced.
  lock.exec('PRAGMA busy_timeout = 1000; BEGIN; SELECT count(*) FROM sqlite_schema');
  const partial = `${destination}.partial`;
  const destinationWal = `${destination}-wal`;
  // Claim the timestamp before touching its sidecar. A repeated clock value
  // must not let a second restore overwrite an earlier pair or its staging file.
  if (sourceLocked) {
    // POSIX releases a process's SQLite locks when that process closes any
    // descriptor for the same inode, including one used for a raw file copy.
    await runSqliteFileJob({ kind: 'copy-locked-database', source, target: partial });
  } else {
    await copyFile(source, partial, constants.COPYFILE_EXCL);
  }
  const unpublished = [partial];
  try {
    if (existsSync(destination) || existsSync(destinationWal)) {
      throw new Error(`Pre-restore copy already exists at ${destination}`);
    }
    if (wal) {
      unpublished.unshift(destinationWal); // Release the staging claim last on failure.
      await copyFile(wal, destinationWal);
    }
    // Listing, restore selection and retention all discover the main .db name.
    // Publish it on the backup filesystem only after every copy has completed.
    renameWithWindowsRetry(partial, destination);
  } catch (error) {
    removeRestoreStagingFiles(unpublished);
    throw error;
  }
}

/**
 * The live database's AUTOINCREMENT counters. Best effort: a database too
 * damaged to read them yields none, and the restore still goes ahead.
 */
function readAutoincrementCounters(dbPath: string, liveLock: Database | null): Array<{ name: string; seq: number }> {
  try {
    const db = liveLock ?? new Database(dbPath, { readwrite: true, create: false });
    try {
      const hasTable = db.query("SELECT 1 FROM sqlite_master WHERE name = 'sqlite_sequence'").get();
      if (!hasTable) return [];
      return db.query('SELECT name, seq FROM sqlite_sequence').all() as Array<{ name: string; seq: number }>;
    } finally {
      if (!liveLock) db.close();
    }
  } catch (error) {
    logger.warn('BACKUP', 'Could not read the live database AUTOINCREMENT counters; restored ids may repeat', { dbPath }, error instanceof Error ? error : new Error(String(error)));
    return [];
  }
}

/**
 * Raise the staged database's AUTOINCREMENT counters to at least the live
 * ones, so rows written after the restore never reuse an id the replaced
 * database already handed out. Chroma documents and cloud-sync ops are keyed
 * by those ids; a reused id would attach old vectors or a stale origin id to
 * a new row.
 */
function carryAutoincrementCounters(stagedDb: string, counters: Array<{ name: string; seq: number }>): void {
  if (counters.length === 0) return;
  const db = new Database(stagedDb, { readwrite: true, create: false });
  try {
    const tables = new Set((db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all() as Array<{ name: string }>).map(row => row.name));
    if (!tables.has('sqlite_sequence')) return;
    const raise = db.prepare('UPDATE sqlite_sequence SET seq = ?1 WHERE name = ?2 AND seq < ?1');
    const insert = db.prepare('INSERT INTO sqlite_sequence (name, seq) SELECT ?2, ?1 WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = ?2)');
    db.transaction(() => {
      for (const { name, seq } of counters) {
        if (!tables.has(name)) continue;
        raise.run(seq, name);
        insert.run(seq, name);
      }
    })();
    raise.finalize();
    insert.finalize();
  } finally {
    db.close();
  }
}

/**
 * Replace the live database with a snapshot, crash-consistently. The heavy
 * whole-file steps run in a child process (sqlite-file-job.ts), so the worker
 * keeps answering requests while a multi-GB restore runs.
 *
 * Order matters. At every point a crash leaves either the old database or
 * the new one, each complete in its main file:
 *   1. Stage a copy of the snapshot (and its -wal, if any) next to the live
 *      file and make it one standalone, quick_check-verified file. Nothing
 *      live has been touched yet.
 *   2. Checkpoint the live database (TRUNCATE) so its main file holds every
 *      committed row. On POSIX, retain an exclusive lock through the swap.
 *   3. Copy the live main file into preRestoreDir as a snapshot-named file,
 *      so `restore` can put it back. A database too damaged to checkpoint is
 *      still restorable; its copy is the db and -wal as they were on disk
 *      before anything opened them.
 *   4. Raise the staged AUTOINCREMENT counters to the live ones.
 *   5. Move the live -wal/-shm aside (they must never sit next to the new
 *      main file), then rename the staged file over the live one (atomic on
 *      one filesystem).
 * A failure before the rename leaves the old database in place, with its
 * sidecars moved back, and removes the staged copy; nothing is ever copied
 * over the live file.
 */
export async function swapDatabaseFromSnapshot(
  dbPath: string,
  snapshotPath: string,
  options: SwapOptions,
): Promise<SwapResult> {
  if (!existsSync(snapshotPath)) {
    throw new Error(`snapshot not found: ${snapshotPath}`);
  }
  const rename = options.renameSync ?? ((from: string, to: string) => renameWithWindowsRetry(from, to));
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
  const attempt = randomUUID();
  const stagedDb = `${dbPath}.restore-staging-${attempt}`;
  const rawCopy = `${dbPath}.restore-raw-${attempt}`;
  let preRestoreCopy: string | null = null;
  let retainedRawCopy: string | null = null;
  let liveLock: Database | null = null;
  const movedSidecars: string[] = [];

  try {
    await copyFile(snapshotPath, stagedDb);
    if (existsSync(`${snapshotPath}-wal`)) await copyFile(`${snapshotPath}-wal`, `${stagedDb}-wal`);
    // Refuse snapshots this binary cannot open before checkpointing or
    // replacing the healthy live database. The startup writer guard would
    // otherwise discover the incompatibility only after the swap committed.
    await runSqliteFileJob({ kind: 'standalone', target: stagedDb, maxSchemaVersion: LATEST_SCHEMA_VERSION });
    // Keep the catch-up marker in the replacement file so the swap and its
    // recovery boundary survive the same crash or restart.
    {
      using staged = new Database(stagedDb, { readwrite: true, create: false });
      stageRestoreCatchUp(staged, options.restoreCatchUpScope);
    }

    if (existsSync(dbPath)) {
      // Keep a byte-for-byte copy of the live db and its -wal before anything
      // opens them: opening a damaged database can make SQLite discard its
      // WAL, and for such a database this copy is the only way back.
      const copyPath = join(options.preRestoreDir, `claude-mem-${ts}-pre-restore.db`);
      await copyFile(dbPath, rawCopy);
      const rawWal = existsSync(`${dbPath}-wal`) ? `${rawCopy}-wal` : undefined;
      if (rawWal) await copyFile(`${dbPath}-wal`, rawWal);
      const dropRawCopy = (): void => {
        removeIfPresent(rawCopy);
        removeIfPresent(`${rawCopy}-wal`);
      };

      let checkpointed: boolean;
      try {
        ({ checkpointed, liveLock } = await checkpointWithRetry(dbPath, options.busyRetryWindowMs ?? 0));
      } catch (error) {
        // Refused: the live database stays as it is and needs no copy.
        dropRawCopy();
        throw error;
      }
      if (checkpointed) {
        // The main file has every committed row. The raw pair could have been
        // taken mid-checkpoint by another process, so it is not kept.
        dropRawCopy();
        await publishPreRestoreCopy(dbPath, copyPath, { sourceLocked: liveLock !== null });
        carryAutoincrementCounters(stagedDb, readAutoincrementCounters(dbPath, liveLock));
      } else {
        // Too damaged to open, so nothing else can be using it either: the
        // raw pair is the best copy there is. Backups may be on another
        // filesystem, so copy both files before discarding either original.
        // If that transfer fails, keep the pair: SQLite may already have
        // discarded the live WAL while trying to open the damaged database.
        retainedRawCopy = rawCopy;
        await publishPreRestoreCopy(rawCopy, copyPath, { wal: rawWal });
        retainedRawCopy = null;
        dropRawCopy();
        logger.warn('BACKUP', 'Restoring over a database that could not be read; new ids may repeat ids it used', { dbPath });
      }
      preRestoreCopy = copyPath;
    }

    // Move the live sidecars aside rather than deleting them: if the rename
    // below fails they go back, so a -wal that still held committed frames
    // (a database too damaged to checkpoint) is never lost.
    for (const ext of SIDECAR_EXTS) {
      if (existsSync(`${dbPath}${ext}`)) {
        fsRenameSync(`${dbPath}${ext}`, `${stagedDb}.live${ext}`);
        movedSidecars.push(ext);
      }
    }
    rename(stagedDb, dbPath);
  } catch (error) {
    for (const ext of movedSidecars) {
      try {
        fsRenameSync(`${stagedDb}.live${ext}`, `${dbPath}${ext}`);
      } catch (restoreError) {
        logger.error('BACKUP', 'Could not put a live sidecar back after a failed restore', { sidecar: `${dbPath}${ext}`, parkedAt: `${stagedDb}.live${ext}` }, restoreError instanceof Error ? restoreError : new Error(String(restoreError)));
      }
    }
    const disposableRaw = retainedRawCopy ? [] : [rawCopy, `${rawCopy}-wal`];
    removeRestoreStagingFiles([stagedDb, ...SIDECAR_EXTS.map(ext => `${stagedDb}${ext}`), ...disposableRaw]);
    if (retainedRawCopy) {
      logger.error('BACKUP', 'Recovery copy transfer failed; raw database and WAL retained', { rawCopy: retainedRawCopy });
    }
    throw error instanceof Error ? error : new Error(String(error));
  } finally {
    liveLock?.close();
  }

  // The swap has committed. A cleanup failure must not report that the old
  // database is still live or prevent the semantic index from being rebuilt.
  // The parked sidecars cannot be mistaken for the new database's sidecars.
  for (const ext of movedSidecars) {
    const leftover = `${stagedDb}.live${ext}`;
    try {
      removeIfPresent(leftover);
    } catch (error) {
      logger.warn('BACKUP', 'Database restored; could not remove a parked old sidecar', { leftover }, error instanceof Error ? error : new Error(String(error)));
    }
  }
  logger.info('BACKUP', 'Database swapped from snapshot', { snapshot: snapshotPath, preRestoreCopy });
  return { preRestoreCopy };
}

/**
 * The semantic index still describes the replaced database: rows deleted or
 * edited after the snapshot come back older than their vectors, and the
 * backfill watermarks sit past them. Flag every project for a rebuild from
 * zero, the same path a dropped corrupt collection takes; the next backfill
 * re-upserts every row. Failure only leaves search stale, so it is logged.
 */
function queueSemanticIndexRebuild(): void {
  try {
    ChromaSyncState.markAllForRebuild();
  } catch (error) {
    logger.error('BACKUP', 'Could not flag the semantic index for a rebuild after the restore; semantic search may miss restored rows', {}, error instanceof Error ? error : new Error(String(error)));
  }
}

/** The cache service has not started yet; remove pre-restore bodies directly. */
function invalidateSessionStartCache(): void {
  try {
    for (const fileName of listContextCacheFiles()) {
      try {
        unlinkSync(join(contextCacheDir(), fileName));
      } catch (error) {
        logger.warn('BACKUP', 'Database restored; could not remove a stale SessionStart block', { fileName },
          error instanceof Error ? error : new Error(String(error)));
      }
    }
  } catch (error) {
    logger.warn('BACKUP', 'Database restored; could not list stale SessionStart blocks', {},
      error instanceof Error ? error : new Error(String(error)));
  }
  // Keep variants.json: the new cache service uses it to render these variants
  // from the restored database. Successfully removed blocks take the live path
  // during that startup gap; cleanup failures above are reported separately.
}

/**
 * Apply a restore staged by `npx claude-mem restore`, before anything in
 * this process opens the database. The marker is cleared as soon as it is
 * read, so a restore that fails is reported once and never retried on every
 * boot. The outcome goes to last-restore.json, which GET /api/backup/status
 * reports. Never throws.
 */
export async function applyPendingRestore(
  dbPath: string,
  backupsDir: string,
  options: Pick<SwapOptions, 'busyRetryWindowMs' | 'restoreCatchUpScope'> = {},
): Promise<LastRestoreResult | null> {
  let snapshot = '(unreadable restore marker)';
  let result: LastRestoreResult;
  try {
    const pending = readPendingRestore();
    if (pending === null) return null;
    snapshot = pending.snapshot;
    clearPendingRestore();
    const snapshotPath = resolveSnapshotInside(backupsDir, pending.snapshot);
    if (snapshotPath === null) {
      throw new Error(`refusing a restore target outside the backups directory: ${pending.snapshot}`);
    }
    const { preRestoreCopy } = await swapDatabaseFromSnapshot(dbPath, snapshotPath, {
      preRestoreDir: backupsDir,
      ...options,
    });
    result = { snapshot, at: Date.now(), ok: true, preRestoreCopy, error: null };
    logger.info('BACKUP', 'Pending restore applied', { snapshot, preRestoreCopy });
    invalidateSessionStartCache();
    queueSemanticIndexRebuild();
  } catch (error) {
    const normalized = error instanceof Error ? error : new Error(String(error));
    // A marker that cannot be read or applied is cleared, never retried on
    // every boot; the failure is reported through last-restore.json.
    try {
      clearPendingRestore();
    } catch (clearError) {
      logger.error('BACKUP', 'Could not clear the restore marker', {}, clearError instanceof Error ? clearError : new Error(String(clearError)));
    }
    result = { snapshot, at: Date.now(), ok: false, preRestoreCopy: null, error: normalized.message };
    logger.error('BACKUP', 'Pending restore FAILED; the worker is starting on the unchanged database', { snapshot }, normalized);
  }
  try {
    writeLastRestoreResult(result);
  } catch (error) {
    logger.error('BACKUP', 'Could not record the restore outcome in last-restore.json', { ok: result.ok }, error instanceof Error ? error : new Error(String(error)));
  }
  return result;
}