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

7.5 KB
Raw Blame
import { describe, expect, it } from 'bun:test';
import { mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';

const repoRoot = process.cwd();
const childScript = `
  import { Database } from 'bun:sqlite';
  import { SessionStore } from './src/services/sqlite/SessionStore.ts';
  import { generateContext } from './src/services/context/ContextBuilder.ts';
  import { ModeManager } from './src/services/domain/ModeManager.ts';
  ModeManager.getInstance().loadMode('code');
  const dbPath = process.env.CLAUDE_MEM_DATA_DIR + '/claude-mem.db';
  if (process.env.READONLY_CASE === 'missing') {
    const text = await generateContext({ projects: ['readonly-parent'] });
    console.log(JSON.stringify({ text, exists: await Bun.file(dbPath).exists() }));
    process.exit(0);
  }

  const store = new SessionStore(dbPath);
  const parentSession = store.createSDKSession('native-content', 'readonly-parent', 'native prompt');
  store.ensureMemorySessionIdRegistered(parentSession, 'native-memory');
  store.storeObservation('native-memory', 'readonly-parent', {
    type: 'discovery', title: 'NATIVE_READONLY_RECORD', subtitle: null,
    facts: [], narrative: 'native narrative', concepts: ['how-it-works'],
    files_read: [], files_modified: [],
  }, 1, 0, 1_700_000_000_000);
  const adoptedSession = store.createSDKSession('adopted-content', 'readonly-child', 'adopted prompt');
  store.ensureMemorySessionIdRegistered(adoptedSession, 'adopted-memory');
  store.storeObservation('adopted-memory', 'readonly-child', {
    type: 'discovery', title: 'ADOPTED_READONLY_RECORD', subtitle: null,
    facts: [], narrative: 'adopted narrative', concepts: ['how-it-works'],
    files_read: [], files_modified: [],
  }, 1, 0, 1_700_000_000_001);
  store.db.prepare('UPDATE observations SET merged_into_project = ? WHERE title = ?').run('readonly-parent', 'ADOPTED_READONLY_RECORD');
  store.close();

  if (process.env.READONLY_CASE === 'statement-lifecycle') {
    const statements = [];
    const prepare = Database.prototype.prepare;
    Database.prototype.prepare = function (...args) {
      const statement = prepare.apply(this, args);
      statements.push(statement);
      return statement;
    };
    try {
      const renders = [];
      for (let index = 0; index < 3; index++) {
        const text = await generateContext({ projects: ['readonly-parent'] });
        renders.push({ text, queries: statements.length, unfinalized: statements.filter(statement => statement.toString() !== '').length });
      }
      console.log(JSON.stringify({ renders }));
    } finally {
      Database.prototype.prepare = prepare;
      for (const statement of statements) statement.finalize();
    }
    process.exit(0);
  }

  const writer = new Database(dbPath);
  const before = {
    schema: (writer.prepare('SELECT COUNT(*) as count FROM schema_versions').get() as { count: number }).count,
    observations: (writer.prepare('SELECT COUNT(*) as count FROM observations').get() as { count: number }).count,
    summaries: (writer.prepare('SELECT COUNT(*) as count FROM session_summaries').get() as { count: number }).count,
  };
  writer.run('BEGIN IMMEDIATE');
  writer.prepare(
    'INSERT INTO observations ('
      + 'memory_session_id, project, text, type, title, subtitle, facts, narrative, '
      + 'concepts, files_read, files_modified, prompt_number, discovery_tokens, '
      + 'created_at, created_at_epoch'
      + ') VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
  ).run(
    'native-memory',
    'readonly-parent',
    'uncommitted text',
    'discovery',
    'UNCOMMITTED_READONLY_RECORD',
    null,
    '[]',
    'uncommitted narrative',
    '["how-it-works"]',
    '[]',
    '[]',
    1,
    0,
    '2023-11-14T22:13:22.000Z',
    1_700_000_002_000,
  );
  const writerPending = (writer.prepare('SELECT COUNT(*) as count FROM observations WHERE title = ?').get('UNCOMMITTED_READONLY_RECORD') as { count: number }).count;
  const text = await generateContext({ projects: ['readonly-parent'] });
  const committedReader = new Database(dbPath, { readonly: true, create: false });
  const visible = {
    schema: (committedReader.prepare('SELECT COUNT(*) as count FROM schema_versions').get() as { count: number }).count,
    observations: (committedReader.prepare('SELECT COUNT(*) as count FROM observations').get() as { count: number }).count,
    summaries: (committedReader.prepare('SELECT COUNT(*) as count FROM session_summaries').get() as { count: number }).count,
    pendingRows: (committedReader.prepare('SELECT COUNT(*) as count FROM observations WHERE title = ?').get('UNCOMMITTED_READONLY_RECORD') as { count: number }).count,
  };
  committedReader.close();
  writer.run('ROLLBACK');
  const after = {
    schema: (writer.prepare('SELECT COUNT(*) as count FROM schema_versions').get() as { count: number }).count,
    observations: (writer.prepare('SELECT COUNT(*) as count FROM observations').get() as { count: number }).count,
    summaries: (writer.prepare('SELECT COUNT(*) as count FROM session_summaries').get() as { count: number }).count,
  };
  const integrity = (writer.prepare('PRAGMA integrity_check').get() as { integrity_check: string }).integrity_check;
  writer.close();
  console.log(JSON.stringify({ text, before, writerPending, visible, after, integrity }));
`;

function runChild(dataDir: string, extraEnv: Record<string, string>): Record<string, any> {
  const result = Bun.spawnSync([process.execPath, '-e', childScript], {
    cwd: repoRoot,
    env: {
      ...process.env,
      CLAUDE_MEM_DATA_DIR: dataDir,
      CLAUDE_CONFIG_DIR: dataDir,
      CLAUDE_MEM_MODES_DIR: join(repoRoot, 'plugin', 'modes'),
      ...extraEnv,
    },
  });
  if (result.exitCode !== 0) {
    throw new Error(new TextDecoder().decode(result.stderr));
  }
  return JSON.parse(new TextDecoder().decode(result.stdout).trim());
}

describe('context database ownership', () => {
  it('releases all query statements on repeated read-only context renders', () => {
    const dataDir = mkdtempSync(join(tmpdir(), 'claude-mem-context-'));
    try {
      const result = runChild(dataDir, { READONLY_CASE: 'statement-lifecycle' });
      expect(result.renders).toHaveLength(3);
      for (const render of result.renders) {
        expect(render.text).toContain('NATIVE_READONLY_RECORD');
        expect(render.text).toContain('ADOPTED_READONLY_RECORD');
        expect(render.queries).toBeGreaterThan(0);
        expect(render.unfinalized).toBe(0);
      }
    } finally {
      rmSync(dataDir, { recursive: true, force: true });
    }
  });

  it('does not create a database for an absent context store', () => {
    const dataDir = mkdtempSync(join(tmpdir(), 'claude-mem-context-'));
    try {
      const result = runChild(dataDir, { READONLY_CASE: 'missing' });
      expect(result.text).toBe('');
      expect(result.exists).toBe(false);
    } finally {
      rmSync(dataDir, { recursive: true, force: true });
    }
  });

  it('reads committed native and adopted records without changing database state', () => {
    const dataDir = mkdtempSync(join(tmpdir(), 'claude-mem-context-'));
    try {
      const result = runChild(dataDir, {});
      expect(result.text).toContain('NATIVE_READONLY_RECORD');
      expect(result.text).toContain('ADOPTED_READONLY_RECORD');
      expect(result.text).not.toContain('UNCOMMITTED_READONLY_RECORD');
      expect(result.writerPending).toBe(1);
      expect(result.visible).toEqual({ ...result.before, pendingRows: 0 });
      expect(result.after).toEqual(result.before);
      expect(result.integrity).toBe('ok');
    } finally {
      rmSync(dataDir, { recursive: true, force: true });
    }
  });
});